Good afternoon,
I am working on a React/Redux app and the images that are being loaded into my store are not displaying. My galleryObject.js includes information about each image I want to display like so:
pastry1: {
name: "Pastry!",
image: "./client/images/cake1.jpg",
desc: "Tasty Pastry"
},
pastry2: {
name: "Pastry!",
image: "./client/images/cake2.jpg",
desc: "Tasty Pastry"
} ... (all the way to pastry17)
What baffles me is that the absolute path does not lead to the image being displayed, the state is being loaded correctly because I can see it in my React dev tools. I even threw in a hyperlink to an image online and it works to test it out.
My file structure is like so:
// Project
// client
//images (where the actual pictures are stored)
//data (where galleryObject.js resides)
//main.js (where everything eventually becomes bundled
In my experience this is normally a problem with how my devServer.js accesses static files in my project. The real admission here is that I copy pasta-d this devServer.js from Wes Bos' Learn Redux tutorial and this is what it looks like:
devServer.js
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');
var PORT = process.env.PORT || 7770
var app = express();
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(PORT, "localhost", function(err) {
if (err) {
console.log(err);
return;
}
console.log(__dirname);
console.log('Listening at http://localhost:7770');
});
Seeing a lot of webpack stuff I figured that is where I am going wrong so I checked out tcoopman's image-webpack-loader. I npm installed the module and my webpack.config.dev/prod.js both look the same as the example from tcoopman:
webpack.config.dev.js:
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: [
'webpack-hot-middleware/client',
'./client/main'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [
// js
{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'client')
},
// CSS
{
test: /\.css$/,
include: path.join(__dirname, 'client'),
loader: 'style-loader!css-loader!stylus-loader'
},
// images
{
test: /\.(jpe?g|png|gif|svg)$/i,
include: path.join(__dirname, 'client'),
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
}
]
}
};
webpack.config.prod.js:
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'source-map',
entry: [
'./client/main'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': "'production'"
}
}),
new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
],
module: {
loaders: [
// js
{
test: /\.js$/,
loaders: ['babel'],
include: path.join(__dirname, 'client')
},
// CSS
{
test: /\.scss$/,
include: path.join(__dirname, 'client'),
loaders: ["style", "css", "sass"]
},
// IMAGES
{
test: /\.(jpe?g|png|gif|svg)$/i,
include: path.join(__dirname, 'client'),
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
}
]
}
};
I'm certain that my combination of copy pasta and lack of knowledge when it comes to web pack are at fault. Bad dev. But I'd really appreciate some insight as to what else I am doing wrong not getting my images to display.
Cheers
edit showing how the images make it into the store:
project/client/store.js
import { createStore, compose } from "redux";
import { syncHistoryWithStore } from "react-router-redux";
import { browserHistory } from "react-router";
// all roots
// root reducer
import rootReducer from "./reducers/mainReducer";
// data Objects
import cakeGallery from './data/galleryObject'; // the object is passed into the default state
// default state object
const defaultState = {
cakeGallery,
open: false
};
const store = createStore(rootReducer, defaultState);
export const history = syncHistoryWithStore(browserHistory, store);
export default store;
project/client/reducers/cakeGalleryReducer.js
function cakeGallery(state={}, action){
console.log("cake gallery reducer")
console.log(state, action);
return state;
}
export default cakeGallery; // this gets combined with another reducer
// in project/client/reducers/mainReducer.js
I think here is where I run into trouble. When the page is loaded the cakeGalleryReducer.js function is firing off, so am I passing an empty object continually? This is a picture of my javascript console when the page loads initially, it still seems like I have an object that should be full.
project/client/components/App.js
// this file is basically creating a component that will
// "sprinkle on" props and dispatchers to our Main component
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import * as actionCreators from "../actions/userActions.js";
import StoreShell from "./StoreShell.js";
// cakeGallery is now known simply as images when referred to in components
function mapStateToProps(state){
return {
images: state.cakeGallery,
open: state.open
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators(actionCreators, dispatch);
}
const App = connect(mapStateToProps, mapDispatchToProps)(StoreShell);
// immediately call what component you want to connect to (Main)
export default App;
project/client/components/StoreShell.js
import Main from "./Main"
const StoreShell = React.createClass({
render(){
return(
<div>
<Main {...this.props} />
</div>
)
}
})
export default StoreShell;
From here the information in the intial galleryObject.js accessible as {this.props.images}.
Webpack is not that smart to import images for you.
I suggest you to import all images required in your galleryObject.js, and keep a reference of the image in each pastry object. Then when it gets to Main component, you can just use them directly.
Check it out
devServer.js
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config.dev');
var PORT = process.env.PORT || 7770
var app = express();
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
// SOLVED IT
app.use(express.static(path.join(__dirname + "/client")));
app.use(require('webpack-hot-middleware')(compiler));
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(PORT, "localhost", function(err) {
if (err) {
console.log(err);
return;
}
console.log(__dirname);
console.log('Listening at http://localhost:7770');
});
So this line: app.use(express.static(path.join(__dirname + "/client"))); was not originally in my copy pasta'd devServer.js. What I did was make my static files (css, javascript, and most importantly images) accessible using the express.static middleware that allows you to serve up static files.
This is how I normally solve this issue but I assumed that images were already covered in the code above and below my soluton.
Thanks for everyone's input.
Related
I updated React to v18 and my Webpack dev server gives me a console error whenever the hot module replacement fires and injects the new javascript code:
Warning: You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before. Instead, call root. render() on the existing root instead if you want to update it.
index.js file
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.jsx';
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<App />);
if (module.hot) module.hot.accept(function (err) {
console.log('An error occurred while accepting new version');
});
webpack.config.js
const path = require('path');
const HtmlWEbpackPlugin = require('html-webpack-plugin');
module.exports = (env) => {
let cfg = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.[contenthash:6].js',
publicPath: '/',
clean: true
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
]
},
plugins: [new HtmlWEbpackPlugin({ template: './src/index.html' })
],
devServer: {
static: {
directory: path.join(__dirname, 'public'),
},
compress: true,
port: 3000,
hot: true,
open: true,
},
performance: {
hints: false
}
}
return cfg;
};
React 18 has native support for hot reloading, this is called Fast Refresh. An excerpt from the react-refresh readme:
Fast Refresh is a feature that lets you edit React components in a running application without losing their state. It is similar to an old feature known as "hot reloading", but Fast Refresh is more reliable and officially supported by React.
To use this with Webpack 5, you will need a plugin called react-refresh-webpack-plugin. To get it to work I would recommend taking a look at the examples included in the git repository, especially the webpack-dev-server example.
NOTE: As of writing this answer, the react-refresh-webpack-plugin is in an experimental state but create-react-app is already using it, so it is probably stable enough to use.
The following is taken straight from react-refresh-webpack-plugin's webpack-dev-server example:
src/index.js
import { createRoot } from 'react-dom/client';
import App from './App';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<App />);
webpack.config.js
const path = require('path');
const ReactRefreshPlugin = require('#pmmmwh/react-refresh-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const isDevelopment = process.env.NODE_ENV !== 'production';
module.exports = {
mode: isDevelopment ? 'development' : 'production',
devServer: {
client: { overlay: false },
},
entry: {
main: './src/index.js',
},
module: {
rules: [
{
test: /\.jsx?$/,
include: path.join(__dirname, 'src'),
use: 'babel-loader',
},
],
},
plugins: [
isDevelopment && new ReactRefreshPlugin(),
new HtmlWebpackPlugin({
filename: './index.html',
template: './public/index.html',
}),
].filter(Boolean),
resolve: {
extensions: ['.js', '.jsx'],
},
};
babel.config.js
module.exports = (api) => {
// This caches the Babel config
api.cache.using(() => process.env.NODE_ENV);
return {
presets: [
'#babel/preset-env',
// Enable development transform of React with new automatic runtime
['#babel/preset-react', { development: !api.env('production'), runtime: 'automatic' }],
],
// Applies the react-refresh Babel plugin on non-production modes only
...(!api.env('production') && { plugins: ['react-refresh/babel'] }),
};
};
You can remove the following from your Webpack entry point:
src/index.js
// ...
if (module.hot) {
module.hot.accept()
}
This has the small drawback that whenever you modify your entry point (src/index.js) a full reload is necessary. Webpack is very in your face about needing to do a full reload, showing you the following log messages.
This really annoyed me. When looking at how create-react-app solved this, I found that they disabled client side logging for the webpack-dev-server, or at least set the log level to warn or error. You can set the log level by setting the client.logging property in the devServer configuration:
webpack.config.js
// ...
devServer: {
client: {
overlay: false,
logging: 'warn' // Want to set this to 'warn' or 'error'
}
}
// ...
What the odd thing is about the "warning", is that it is not a warning at all, it is just an info message dressed up as a warning.
Hope this helps.
I have divided my configuration in to two production and development mode and merging them using webpack-merge.
Whenever i try to build or run the code it gives me you may need an appropriate loader error even though i have define loader for the jsx or js files.
Common Config File code is here...
const path = require("path");
const HtmlWebpackPlugin = require('html-webpack-plugin'); //installed via npm
const webpack = require('webpack'); //to access built-in plugins
module.exports = {
entry : "./src/index.js",
module: {
rules: [
{
test: /\.scss$/,
use: [
"style-loader",
"css-loader",
"sass-loader"
]
},
{
test: /.(js|jsx)$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015', 'react']
}
}
]
},
plugins: [
new webpack.ProgressPlugin(),
new HtmlWebpackPlugin({template: './src/index.html'})
]
}
Production Config Code is
const path = require("path");
const common = require("./webpack.config");
const merge = require("webpack-merge");
module.exports = (common, {
mode : "production",
output: {
filename : "bundle.[contentHash].js",
path : path.resolve(__dirname, "dist")
}
});
Development Config Code
const path = require("path");
const common = require("./webpack.config.js");
const merge = require("webpack-merge");
module.exports = (common, {
mode : "development",
output: {
filename : "bundle.js",
path : path.resolve(__dirname, "dist")
}
});
index.js code
import "./assets/scss/main.scss";
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
return <h1>Hello</h1>
}
}
ReactDOM.render(<App/>, document.getElementById('app'));
.babelrc code
{
"presets": ["env", "react","#babel/preset-env"],
"plugins": [
"transform-class-properties"
]
}
You will need to call merge on both your files, merging common with the object specified for each case:
// webpack.prod.js
const path = require("path");
const common = require("./webpack.config");
const merge = require("webpack-merge");
module.exports = merge(common, {
mode : "production",
output: {
filename : "bundle.[contentHash].js",
path : path.resolve(__dirname, "dist")
}
});
// webpack.dev.js
const path = require("path");
const common = require("./webpack.config.js");
const merge = require("webpack-merge");
module.exports = merge(common, {
mode : "development",
output: {
filename : "bundle.js",
path : path.resolve(__dirname, "dist")
}
});
That error occurs because your JSX is not being compiled to JavaScript.
The test in your config file that handles this is:
test: /.(js|jsx)$/,
loader: 'babel-loader',
I see that you've imported "webpack-merge" but it does not appear that you're using it (at least in the code that is displayed in your question).So it seems like you're not merging the disparate config files in the way you're expecting (or maybe at all).
Instead of splitting your config into multiple files, usually [from what I've seen] developers prefer to use one file with some logic in it based on an environmental variable: https://webpack.js.org/guides/environment-variables/
process.env.NODE_ENV === 'dev' ? doDevStuff : doProdStuff
I'm writing an electron app with react. I run the developement version using this command:
webpack-dev-server --hot --host 0.0.0.0 --port 4000 --config=./webpack.dev.config.js
Here is the webpack.dev.config.js file
const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { spawn } = require('child_process');
const helpers = require('./config/helpers');
// Config directories
const SRC_DIR = path.resolve(__dirname, 'src');
const OUTPUT_DIR = path.resolve(__dirname, 'dist');
// Any directories you will be adding code/files into, need to be added to this array so webpack will pick them up
const defaultInclude = [SRC_DIR];
module.exports = {
entry: SRC_DIR + '/index.js',
output: {
path: OUTPUT_DIR,
publicPath: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.css$/,
use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
include: defaultInclude
},
{
test: /\.jsx?$/,
use: [{ loader: 'babel-loader' }],
include: defaultInclude
},
{
test: /\.(jpe?g|png|gif)$/,
use: [{ loader: 'file-loader?name=img/[name]__[hash:base64:5].[ext]' }],
include: defaultInclude
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [{ loader: 'file-loader?name=font/[name]__[hash:base64:5].[ext]' }],
include: defaultInclude
}
]
},
target: 'electron-renderer',
plugins: [
new HtmlWebpackPlugin({
template: helpers.root('public/index.html'),
inject: 'body'
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development')
})
],
devtool: 'cheap-source-map',
devServer: {
contentBase: OUTPUT_DIR,
stats: {
colors: true,
chunks: false,
children: false
},
setup() {
spawn(
'electron',
['.'],
{ shell: true, env: process.env, stdio: 'inherit' }
)
.on('close', code => {
console.error("electron exited with code ", code);
process.exit(0)
})
.on('error', spawnError => console.error(spawnError));
}
}
};
Once the electron browser opens it has the following error in the Dev-Tools console.
Uncaught ReferenceError: require is not defined
at Object.url (index.js:23)
at __webpack_require__ (bootstrap:709)
at fn (bootstrap:94)
at Object../node_modules/webpack-dev-server/client/utils/createSocketUrl.js (createSocketUrl.js:4)
at __webpack_require__ (bootstrap:709)
at fn (bootstrap:94)
at Object.<anonymous> (client:20)
at Object../node_modules/webpack-dev-server/client/index.js?http://0.0.0.0:4000 (client:176)
at __webpack_require__ (bootstrap:709)
at fn (bootstrap:94)
The place where it claims this is occurring is at index.js:23.
Here is the build version of index.js:
import React from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import App from "./components/App";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { ipcRenderer as ipc } from "electron";
import { onUpdate } from "./actions/workerActions";
import { RECEIVED_STATE } from "./actions/types";
import "./assets/css/index.css";
import rootReducer from "./reducers/rootReducer";
import defaultState from "../config/defaultstate"; //Setup redux store
const middleware = [thunk];
const store = createStore(rootReducer, defaultState, applyMiddleware(...middleware));
ipc.on(RECEIVED_STATE, arg => {
console.log("Recieved State: ", arg);
onUpdate(arg)(store.dispatch);
}); // Now we can render our application into it
render(React.createElement(Provider, {
store: store
}, React.createElement(App, null)), document.getElementById("app"));
As you can see require does not appear here and all of the import aside from ipcRender are designed to run client-side, and therefore should not use required. I tried commenting out the ipcRender import but it resulted in the exact same error.
Most puzzlingly of all, I get the exact same error even with the entire index.js file commented out. The console still claiming the block comment contains a reference to require, which is not defined.
If you're using webpack directly then make sure you have the following in the webpack config that targets your renderer code.
// webpack.config.js
...
module.exports = {
...
target: 'web',
...
}
If you're using Vue then you'll need something like the following:
// vue.config.js
...
module.exports = {
...
configureWebpack: {
target: 'web'
},
...
}
Or, in my case I was using vue-cli-plugin-electron-builder and so need the following:
// vue.config.js
...
module.exports = {
...
pluginOptions: {
electronBuilder: {
nodeIntegration: false,
chainWebpackRendererProcess: config => {
config.target('web');
}
}
},
...
}
It turns out that the error is caused by importing electron's ipcRenderer which requires node integration and uses require. The reason that commenting out the import in the index.js didn't fix the error was because it was imported in other files.
I'm referencing an image inside my .JSX file but the generated URL is wrong.
It looks like this : http://localhost:43124/dist/dist/9ee7eb54c0eb428bb30b599ef121fe25.jpg
The folder "dist" exists with the picture but not "dist/dist". I think the problem comes from my Webpack.config.js. Here are the files :
module.d.ts
I instruct Typescript what to do with image files as mentionned here.
declare module '*.jpg'
declare module '*.svg'
Layout.tsx
I reference my logo inside React so it can be packed by Webpack.
/// <reference path="./module.d.ts"/>
import * as React from 'react';
import logo from '../img/logo.svg';
export class Layout extends React.Component<{}, {}> {
public render() {
return <img src="{logo}" width="220" alt="logo" />
}
}
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const CheckerPlugin = require('awesome-typescript-loader').CheckerPlugin;
const merge = require('webpack-merge');
module.exports = (env) => {
const isDevBuild = !(env && env.prod);
// Configuration in common to both client-side and server-side bundles
const sharedConfig = () => ({
stats: { modules: false },
resolve: { extensions: ['.js', '.jsx', '.ts', '.tsx'] },
output: {
filename: '[name].js',
publicPath: 'dist/' // Webpack dev middleware, if enabled, handles requests for this URL prefix
},
module: {
rules: [
{ test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
{ test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=25000' }
]
},
plugins: [new CheckerPlugin()]
});
// Configuration for client-side bundle suitable for running in browsers
const clientBundleOutputDir = './wwwroot/dist';
const clientBundleConfig = merge(sharedConfig(), {
entry: { 'main-client': './ClientApp/boot-client.tsx' },
module: {
rules: [
{ test: /\.css$/, use: ExtractTextPlugin.extract({ use: isDevBuild ? 'css-loader' : 'css-loader?minimize' }) }
]
},
output: { path: path.join(__dirname, clientBundleOutputDir) },
plugins: [
new ExtractTextPlugin('style.css'),
new webpack.DllReferencePlugin({
context: __dirname,
manifest: require('./wwwroot/dist/vendor-manifest.json')
})
].concat(isDevBuild ? [
// Plugins that apply in development builds only
new webpack.SourceMapDevToolPlugin({
filename: '[file].map', // Remove this line if you prefer inline source maps
moduleFilenameTemplate: path.relative(clientBundleOutputDir, '[resourcePath]') // Point sourcemap entries to the original file locations on disk
})
] : [
// Plugins that apply in production builds only
new webpack.optimize.UglifyJsPlugin()
])
});
return [clientBundleConfig];
};
I used the default Visual Studio ASP.NET Core React + Redux template.
How do you use Webpack and AngularJS together, and how about template loading and on demand fetching of resources?
An example of a well written webpack.config.js file for this purpose would be very much appreciated.
All code snippets displayed here can be accessed at this github repo. Code has been generously adapted from this packetloop git repo.
webpack.config.json
var path = require('path');
var ResolverPlugin = require("webpack/lib/ResolverPlugin");
var config = {
context: __dirname,
entry: ['webpack/hot/dev-server', './app/app.js'],
output: {
path: './build',
filename: 'bundle.js'
},
module: {
loaders: [{
test: /\.css$/,
loader: "style!css-loader"
}, {
test: /\.scss$/,
loader: "style!css!sass?outputStyle=expanded"
}, {
test: /\.jpe?g$|\.gif$|\.png$|\.svg$|\.woff$|\.ttf$/,
loader: "file"
}, {
test: /\.html$/,
loader: "ngtemplate?relativeTo=" + path.join(__dirname, 'app/') + "!raw"
}]
},
// Let webpack know where the module folders are for bower and node_modules
// This lets you write things like - require('bower/<plugin>') anywhere in your code base
resolve: {
modulesDirectories: ['node_modules', 'lib/bower_components'],
alias: {
'npm': __dirname + '/node_modules',
'vendor': __dirname + '/app/vendor/',
'bower': __dirname + '/lib/bower_components'
}
},
plugins: [
// This is to help webpack know that it has to load the js file in bower.json#main
new ResolverPlugin(
new ResolverPlugin.DirectoryDescriptionFilePlugin("bower.json", ["main"])
)
]
};
module.exports = config;
To import AngularJS into the main app.js you do the following:
app/vendor/angular.js
'use strict';
if (!global.window.angular) {
require('bower/angular/angular');
}
var angular = global.window.angular;
module.exports = angular;
And then use it in app.js like so,
app.js
...
var angular = require('vendor/angular');
// Declare app level module
var app = angular.module('myApp', []);
...
Is the following correct? Is there an easier way to do this? I've seen a few (not a lot by any standards) posts which listed another method.
From this reddit post comment
// Add to webpack.config.js#module#loaders array
{
test: /[\/]angular\.js$/,
loader: "exports?angular"
}
There is also another plugin which is in development right now, at stackfull/angular-seed. It seems to be in the right direction, but is really really hard to use right now.
Webpack is way awesome, but the lack of documentation and samples are killing it.
You can just require angular in all modules (files) where you need it. I have a github repository with example how to do that (also using webpack for build). In the example ES6 import syntax is used but it shouldnt matter, you can use standard require() instead.
Example:
import 'bootstrap/dist/css/bootstrap.min.css';
import './app.css';
import bootstrap from 'bootstrap';
import angular from 'angular';
import uirouter from 'angular-ui-router';
import { routing} from './app.config';
import common from './common/common.module';
import featureA from './feature-a/feature-a.module';
import featureB from './feature-b/feature-b.module';
const app = angular
.module('app', [uirouter, common, featureA, featureB])
.config(routing);
I am starting with Angular + Flux with Webpack so may be I can help you with some things.
Basically I am installing everything with NPM, it has module export system, so it works like nothing. (You can use export-loader, but why if you do not need to.)
My webpack.config.js looks like this:
var webpack = require('webpack');
var path = require('path');
var HtmlWebpackPlugin = require("html-webpack-plugin");
var nodeModulesDir = path.resolve(__dirname, './node_modules');
// Some of my dependencies that I want
// to skip from building in DEV environment
var deps = [
'angular/angular.min.js',
...
];
var config = {
context: path.resolve(__dirname, './app'),
entry: ['webpack/hot/dev-server', './main.js'],
resolve: {
alias: {}
},
output: {
path: path.resolve(__dirname, './build'),
filename: 'bundle.js'
},
// This one I am using to define test dependencies
// directly in the modules
plugins: [
new webpack.DefinePlugin({
ON_TEST: process.env.NODE_ENV === 'test'
})
],
module: {
preLoaders: [
{test: /\.coffee$/, loader: "coffeelint", exclude: [nodeModulesDir]}
],
loaders: [
{test: /\.js$/, loader: 'ng-annotate', exclude: [nodeModulesDir]},
{test: /\.coffee$/, loader: 'coffee', exclude: [nodeModulesDir]},
...
],
noParse: []
},
devtool: 'source-map'
};
if (process.env.NODE_ENV === 'production') {
config.entry = {
app: path.resolve(__dirname, './app/main.js'),
vendors: ['angular']
};
// config.output.path = path.resolve(__dirname, './dist');
config.output = {
path: path.resolve(__dirname, "./dist"),
filename: "app.[hash].js",
hash: true
};
config.plugins.push(new webpack.optimize.UglifyJsPlugin());
config.plugins.push(new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.[hash].js'));
config.plugins.push(new HtmlWebpackPlugin({
title: 'myApp',
template: path.resolve(__dirname, './app/index.html'),
inject: 'body'
}));
delete config.devtool;
}
else {
deps.forEach(function (dep) {
var depPath = path.resolve(nodeModulesDir, dep);
config.resolve.alias[dep.split(path.sep)[0]] = depPath;
config.module.noParse.push(depPath);
});
}
module.exports = config;
My main.js looks like this:
var angular = require('angular');
if(ON_TEST) {
require('angular-mocks/angular-mocks');
}
require('./index.coffee');
And index.coffee containt main angular module:
ngModule = angular.module 'myApp', []
require('./directive/example.coffee')(ngModule)