webpack --json: Error: 'output.filename' is required - node.js

I have a valid webpack.config.js that I use constantly for development, with the following content:
var path = require('path')
const merge = require('webpack-merge');
const NpmInstallPlugin = require('npm-install-webpack2-plugin');
var webpack = require('webpack')
var ManifestPlugin = require('webpack-manifest-plugin')
var InlineChunkManifestHtmlWebpackPlugin = require('inline-chunk-manifest-html-webpack-plugin')
var WebpackChunkHash = require("webpack-chunk-hash")
var HtmlWebpackPlugin = require('html-webpack-plugin')
var ExtractTextPlugin = require('extract-text-webpack-plugin')
var CleanWebpackPlugin = require('clean-webpack-plugin')
const proxyTarget = 'http://localhost:2246/'
const visitPort = '8056'
const isMinimize =false
const outputFolderName = ''
const TARGET = process.env.npm_lifecycle_event;
isDebug = process.env.NODE_ENV === 'production' ?
true :
false;
const common = {
entry: './src/app.js',
devServer: {
hot: true,
historyApiFallback: true,
noInfo: true
},
performance: {
hints: false
},
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
resolve: {
alias: {
vue: 'vue/dist/vue.js'
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
// Since sass-loader (weirdly) has SCSS as its default parse mode, we map
// the "scss" and "sass" values for the lang attribute to the right configs here.
// other preprocessors should work out of the box, no loader config like this necessary.
'scss': 'vue-style-loader!css-loader!sass-loader',
'sass': 'vue-style-loader!css-loader!sass-loader?indentedSyntax'
}
// other vue-loader options go here
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
},
{
test: /\.(woff|woff2|ttf|eot)(\?\S*)?$/,
loader: 'file-loader',
options: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve : {
alias: {
'vue$': 'vue/dist/vue'
}
}
}
if (process.env.NODE_ENV === 'production') {
module.exports.plugins = [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
]
} else {
module.exports.devtool = '#source-map'
}
if(TARGET === 'build') {
module.exports = merge(common,
{
devtool: 'source-map',
});
}
if(TARGET === "dev-server") {
module.exports = merge(common, {
devtool: 'cheap-module-eval-source-map',
devServer: {
historyApiFallback: true,
hot: true,
inline: true,
stats: true,
noInfo: true,
quiet: true,
stats: 'errors-only',
// host: process.env.HOST,
port: 3001
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new NpmInstallPlugin({
save: true // --save
})
]
});
}
The following npm run commands are in package.json and all of the commands run successfully
"scripts": {
"dev-server": "cross-env NODE_ENV=development webpack-dev-server",
"dev": "cross-env NODE_ENV=development electron ./",
"build": "cross-env NODE_ENV=production webpack --progress --profile --colors",
"start": "cross-env NODE_ENV=production electron ./",
"package": "npm run build; npm run package-osx;
}
Problem
I am trying to use the webpack-bundle-size-analyzer to check the bundled packages. The following command
$ webpack --json | webpack-bundle-size-analyzer
produced this error
/usr/local/lib/node_modules/webpack/bin/convert-argv.js:507
throw new Error("'output.filename' is required, either in config file or as --output-filename");
^
Error: 'output.filename' is required, either in config file or as --output-filename
at processOptions (/usr/local/lib/node_modules/webpack/bin/convert-argv.js:507:11)
at processConfiguredOptions (/usr/local/lib/node_modules/webpack/bin/convert-argv.js:150:4)
at module.exports (/usr/local/lib/node_modules/webpack/bin/convert-argv.js:112:10)
at yargs.parse (/usr/local/lib/node_modules/webpack/bin/webpack.js:171:41)
at Object.Yargs.self.parse (/usr/local/lib/node_modules/webpack/node_modules/yargs/yargs.js:533:18)
at Object.<anonymous> (/usr/local/lib/node_modules/webpack/bin/webpack.js:152:7)
at Module._compile (module.js:573:30)
at Object.Module._extensions..js (module.js:584:10)
at Module.load (module.js:507:32)
at tryModuleLoad (module.js:470:12)
at Function.Module._load (module.js:462:3)
at Function.Module.runMain (module.js:609:10)
at startup (bootstrap_node.js:158:16)
at bootstrap_node.js:598:3
Error: The input is not valid JSON.
Check that:
- You passed the '--json' argument to 'webpack'
- There is no extra non-JSON content in the output, such as log messages.
The parsing error was:
SyntaxError: Unexpected end of JSON input
webpack: 3.6.0
webpack-bundle-size-analyzer: 2.7.0
Additional Notes
I have validated the webpack.config.js file, at the root of project directory
No spelling mistakes in the webpack.config.js file as far as I can see
I just need a simple JSON output from webpack to feed to webpack-bundle-size-analyzer

Related

Electron application cannot resolve any node module that is added to webpack externals

I am trying to build an Electron application using Vue.js.
I am using webpack-dev-server to run the electron app in development mode.
In the webpack config I am adding all my node_modules to the externals array since I do not want them to be bundled.
The webpack development server gets started successfully without any error and the application is also launched as expected but I get the following error in the console.
Uncaught Error: Cannot find module 'frappejs'.
Note: This is not the only module that cannot be resolved. All the modules that I have added to the webpack externals arrays could not be resolved.
If I do not add them to the externals array, the node_modules are detected and the above error disappears.
Another thing that I have noticed is that if I replace
const frappe = require('frappejs'); with
const frappe = require('../../node_modules/frappejs');
The error disappers in this case as well when I am explicitly pointing to the node_modules directory.
What maybe the reason for this behaviour?
config.js
const webpack = require('webpack');
// plugins
const VueLoaderPlugin = require('vue-loader/lib/plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CaseSensitivePathsWebpackPlugin = require('case-sensitive-paths-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const { getAppConfig, resolveAppDir } = require('./utils');
const appDependencies = require(resolveAppDir('./package.json')).dependencies;
const frappeDependencies = require(resolveAppDir('./node_modules/frappejs/package.json')).dependencies;
// const frappeDependencies = require('../package.json').dependencies;
let getConfig, getElectronMainConfig;
function makeConfig() {
const isProduction = process.env.NODE_ENV === 'production';
process.env.ELECTRON = 'true';
const isElectron = process.env.ELECTRON === 'true';
const isMonoRepo = process.env.MONO_REPO === 'true';
const whiteListedModules = ['vue'];
const allDependencies = Object.assign(frappeDependencies, appDependencies);
const externals = Object.keys(allDependencies).filter(d => !whiteListedModules.includes(d));
getConfig = function getConfig() {
const appConfig = getAppConfig();
const config = {
mode: isProduction ? 'production' : 'development',
context: resolveAppDir(),
entry: isElectron ? appConfig.electron.entry : appConfig.dev.entry,
externals: isElectron ? externals : undefined,
target: isElectron ? 'electron-renderer' : 'web',
output: {
path: isElectron ? resolveAppDir('./dist/electron') : resolveAppDir('./dist'),
filename: '[name].js',
// publicPath: appConfig.dev.assetsPublicPath,
libraryTarget: isElectron ? 'commonjs2' : undefined
},
devtool: !isProduction ? 'cheap-module-eval-source-map' : '',
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader'
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: file => (
/node_modules/.test(file) &&
!/\.vue\.js/.test(file)
)
},
{
test: /\.node$/,
use: 'node-loader'
},
{
test: /\.css$/,
use: [
'vue-style-loader',
'css-loader'
]
},
{
test: /\.scss$/,
use: [
'vue-style-loader',
'css-loader',
'sass-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
}
]
},
resolve: {
extensions: ['.js', '.vue', '.json', '.css', '.node'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'deepmerge$': 'deepmerge/dist/umd.js',
'#': appConfig.dev.srcDir ? resolveAppDir(appConfig.dev.srcDir) : null
}
},
plugins: [
new webpack.DefinePlugin(Object.assign({
'process.env': appConfig.dev.env,
'process.env.NODE_ENV': isProduction ? '"production"' : '"development"',
'process.env.ELECTRON': JSON.stringify(process.env.ELECTRON)
}, !isProduction ? {
'__static': `"${resolveAppDir(appConfig.staticPath).replace(/\\/g, '\\\\')}"`
} : {})),
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
template: resolveAppDir(appConfig.dev.entryHtml),
nodeModules: !isProduction
? isMonoRepo ? resolveAppDir('../../node_modules') : resolveAppDir('./node_modules')
: false
}),
new CaseSensitivePathsWebpackPlugin(),
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(),
new FriendlyErrorsWebpackPlugin({
compilationSuccessInfo: {
messages: [`FrappeJS server started at http://${appConfig.dev.devServerHost}:${appConfig.dev.devServerPort}`],
},
}),
new webpack.ProgressPlugin(),
isProduction ? new CopyWebpackPlugin([
{
from: resolveAppDir(appConfig.staticPath),
to: resolveAppDir('./dist/electron/static'),
ignore: ['.*']
}
]) : null,
// isProduction ? new BabiliWebpackPlugin() : null,
// isProduction ? new webpack.LoaderOptionsPlugin({ minimize: true }) : null,
].filter(Boolean),
optimization: {
noEmitOnErrors: false
},
devServer: {
// contentBase: './dist', // dist path is directly configured in express
hot: true,
quiet: true
},
node: {
// prevent webpack from injecting useless setImmediate polyfill because Vue
// source contains it (although only uses it if it's native).
setImmediate: false,
// process is injected via DefinePlugin, although some 3rd party
// libraries may require a mock to work properly (#934)
process: 'mock',
// prevent webpack from injecting mocks to Node native modules
// that does not make sense for the client
dgram: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty',
child_process: 'empty'
}
}
return config;
}
getElectronMainConfig = function getElectronMainConfig() {
const appConfig = getAppConfig();
return {
entry: {
main: resolveAppDir(appConfig.electron.paths.main)
},
externals: externals,
module: {
rules: [
{
test: /\.js$/,
use: 'babel-loader',
exclude: /node_modules/
},
{
test: /\.node$/,
use: 'node-loader'
}
]
},
node: {
__dirname: !isProduction,
__filename: !isProduction
},
output: {
filename: '[name].js',
libraryTarget: 'commonjs2',
path: resolveAppDir('./dist/electron')
},
plugins: [
new webpack.NoEmitOnErrorsPlugin(),
// isProduction && new BabiliWebpackPlugin(),
isProduction && new webpack.DefinePlugin({
'process.env.NODE_ENV': '"production"'
})
].filter(Boolean),
resolve: {
extensions: ['.js', '.json', '.node']
},
target: 'electron-main'
}
}
}
makeConfig();
module.exports = {
getConfig,
getElectronMainConfig
};
Note: the resolveAppDir function returns the cwd path concatenated with the parameter passed.

How to use Development Version of Reactjs with Webpack 4

This is my current webpack configuration. Its been a while since I've had to do this, and the last time I did it webpack 2 was just coming out. At that point there was a plugin that would allow me to define my output. Now that plugin is no longer valid.
What I need to do is use the development version of ReactJS but my builds keep building with the production version. So error handling is next to impossible since react removes a bulk of the errors in a production build.
const fs = require('fs');
const os = require('os');
const path = require('path');
const webpack = require('webpack');
const files = fs.readdirSync('./src/scripts/').filter(function (file) {
return path.extname(file) === '.js';
});
const entries = files.reduce(function (obj, file, index) {
const key = path.basename(file, '.js');
obj[key] = [
'./src/scripts/' + key
];
return obj;
}, {});
entries.hotreload = 'react-hot-loader/patch';
console.log(argv.mode);
module.exports = {
mode: 'development',
entry: entries,
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: ['*', '.js', '.jsx']
},
output: {
path: __dirname + '/dist/scripts',
publicPath: '/',
filename: '[name].js'
},
plugins: [
new webpack.HotModuleReplacementPlugin()
],
devServer: {
contentBase: './dist/scripts',
hot: true
}
};
This is also how I start webpack webpack-dev-server --config ./webpack.config.js --mode development which doesn't seem to do me any good.
Well, I create a script to run the webpack server. This is how I start the dev server npm start.
Here is my scripts:
"scripts": {
"dev": "webpack --mode development",
"start": "webpack-dev-server",
"build": "cross-env NODE_ENV=production webpack-dev-server --client-log-level none --color --compress"
},
And here my webpack.config.js:
const modoDev = process.env.NODE_ENV != "production";
const webpack = require('webpack');
const ExtractTextPlugin = require('mini-css-extract-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');
const path = require('path');
module.exports = {
mode: modoDev ? 'development' : 'production',
entry: './src/index.jsx',
output: {
path: __dirname + '/public',
filename: './app.js',
publicPath: '/'
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true
}),
new OptimizeCssAssetsPlugin({})
]
},
devServer: {
host: '0.0.0.0',
port: 8080,
contentBase: './public',
historyApiFallback: {
index: "/"
},
},
resolve: {
extensions: ['*', '.js', '.jsx'],
alias: {
modules: path.resolve(__dirname + '/node_modules/')
}
},
plugins: [new ExtractTextPlugin({
filename: 'app.css'
}), new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery"
})],
module: {
rules: [{
test: /.js[x]?$/,
exclude: /node_modules/,
use: {
loader: "babel-loader"
}
},
{
test: /\.(sa|sc|c)ss$/,
use: [ExtractTextPlugin.loader, 'css-loader', 'sass-loader']
}, {
test: /\.woff|.woff2|.ttf|.eot|.svg|.png|.jpg*.*$/,
use: ['file-loader']
},
],
}
};

Webpack prod vs dev

In my webpack configuration, I've tried to make separate configuration to my prod and dev enviroments. I'm trying to achieve to different JS files for each task. Meaning, when I build it, I need my code to go to the prod environment with a specific name "lib.js" and when I run my Dev environment, I want the compiled files to go to the "dist" folder.
This is my webpack.config.js file:
const webpack = require('webpack')
const ExtractTextPlugin = require("extract-text-webpack-plugin")
let path = require('path');
let config = {
entry: [
'./src/index.js'
],
module: {
rules: [{
test: /\.jsx?$/,
exclude: /node_modules/,
use: [
'react-hot-loader',
'babel-loader'
]
},
{
test: /\.(css)$/,
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: 'css-loader'
})
},
{
test: /\.less$/,
use:ExtractTextPlugin.extract({
use: 'less-loader'
})
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
loader: 'file-loader',
},
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
}
],
},
resolve: {
extensions: ['*', '.js', '.jsx', '.css'],
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
}
})
],
devServer: {
contentBase: './dist',
historyApiFallback: true
},
devtool : "cheap-module-source-map",
}
if (process.env.NODE_ENV === 'production') {
config.output= {
path: path.join(__dirname, '/build/'),
filename: 'lib.js',
library: ['MyLibrary'],
libraryTarget: 'umd'
};
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({ sourceMap: true }),
new ExtractTextPlugin({
filename: 'bundle.css',
disable: false,
allChunks: true
}),
new webpack.optimize.AggressiveMergingPlugin({
minSizeReduce: 1,
moveToParents: true
})
)
} else {
config.output= {
path: path.join(__dirname, '/dist/'),
filename: 'bundle.js',
library: ['MyLibrary'],
libraryTarget: 'umd',
publicPath: '/dist/'
};
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({ sourceMap: true }),
new ExtractTextPlugin({ disable: true })
)
}
module.exports = config
and these are my scripts:
"scripts": {
"dev": "webpack-dev-server -d --env.platform=default --progress --hot",
"build": "set NODE_ENV=production && webpack -p --progress --hot"
}
What actually happens is that only when I build, the files go to the dist folder, even though I've set the NODE_ENV param to "production".
Would be glad for help.
Thanks!
It could be the trailing space that you have after NODE_ENV=production, which probably sets NODE_ENV to production with a space after which won't match in your webpack config. Try to change it in the package.json like this:
"build": "set NODE_ENV=production&& webpack -p --progress --hot"
This is mentioned in the comment by #daw on this SO answer.

webpack using with nodejs

I am new in reactjs. I am just start learning reactjs. I have problem using webpack in nodejs. I want to create node server which will run the webpack file. I have webpack file:
const {resolve} = require('path');
const webpack = require('webpack');
const validate = require('webpack-validator');
const {getIfUtils, removeEmpty} = require('webpack-config-utils');
module.exports = env => {
const {ifProd, ifNotProd} = getIfUtils(env)
return validate({
entry: './index.js',
context: __dirname,
output: {
path: resolve(__dirname, './build'),
filename: 'bundle.js',
publicPath: '/build/',
pathinfo: ifNotProd(),
},
devtool: ifProd('source-map', 'eval'),
devServer: {
port: 8080,
historyApiFallback: true
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
{test: /\.css$/, loader: 'style-loader!css-loader'},
{test: /(\.eot|\.woff2|\.woff|\.ttf|\.svg)/, loader: 'file-loader'},
],
},
plugins: removeEmpty([
ifProd(new webpack.optimize.DedupePlugin()),
ifProd(new webpack.LoaderOptionsPlugin({
minimize: true,
debug: false,
quiet: true,
})),
ifProd(new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"',
},
})),
ifProd(new webpack.optimize.UglifyJsPlugin({
sourceMap: true,
compress: {
screw_ie8: true, // eslint-disable-line
warnings: false,
},
})),
])
});
};
How can i use this configuration with nodejs. please help
First of all your webpack configuration will not run on webpack 2+, because webpack-validator is deprecated, so I have removed it. I would recommend you to install npm install webpack-dev-server -g globally and use it as a server in your react development. This is how you can modify your configuration to use it (webpack.config.js):
const path = require("path");
const webpack = require('webpack');
const {getIfUtils, removeEmpty} = require('webpack-config-utils');
module.exports = env => {
const {ifProd, ifNotProd} = getIfUtils(env)
return {
entry: [
"webpack-dev-server/client?http://localhost:3003",
"webpack/hot/only-dev-server",
"react-hot-loader/patch"
],
context: __dirname,
output: {
path: path.join(__dirname, './build'),
filename: 'bundle.js',
publicPath: '/build/',
pathinfo: ifNotProd(),
},
devtool: ifProd('source-map', 'eval'),
devServer: {
contentBase: path.join(__dirname, "src"),
// enable HMR
hot: true,
// embed the webpack-dev-server runtime into the bundle
inline: true,
// serve index.html in place of 404 responses to allow HTML5 history
historyApiFallback: true,
port: 3003
},
module: {
loaders: [
{test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader'},
{test: /\.css$/, loader: 'style-loader!css-loader'},
{test: /(\.eot|\.woff2|\.woff|\.ttf|\.svg)/, loader: 'file-loader'},
],
},
plugins: removeEmpty([
//...
// same as before
//...
])
};
};
package.json :
{
...
"dependencies": {},
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.2",
"react-hot-loader": "^3.1.1",
"webpack": "^3.8.1",
"webpack-config-utils": "^2.3.0",
"webpack-dev-server": "^2.9.4",
}
}
in the same folder where webpack.config.js is make one file webpack.development.js, that will just set enviorment:
var config = require('./webpack.config.js')
module.exports = config("development"); // can be "production" or "development"
Files structure:
root
build
bundle.js
src
index.html
index.js
package.json
webpack.config.js
webpack.development.js
At the end just run it:
webpack-dev-server --config webpack.development.js --progress -p --hot -w
--hot - will run server,
-w - watch files
My suggestion:
package.json scripts (install webpack (-g and –save-dev), nodemon (-g and –save-dev) and concurrently (–save-dev))
"scripts": {
"webpack-watch-client": "webpack -w",
"server": "nodemon server",
"dev": "concurrently --kill-others \"npm run webpack-watch-client\" \"npm run server\""
}
webpack.config.js example
'use strict'
const path = require('path');
const PATHS = {
app: path.join(__dirname, 'src'),
public: path.join(__dirname, 'public')
};
module.exports = {
entry: {
app: PATHS.app,
},
output: {
path: PATHS.public,
filename: 'js/bundle.js'
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['react', 'es2015']
}
}
]
},
{
test: /\.css$/,
use: [
{ loader: 'style-loader' },
{ loader: 'css-loader' }
]
},
{
test: /\.(woff|woff2|eot|ttf)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'assets/fonts/'
}
}
]
},
{
test: /\.(png|jpg|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {
outputPath: 'assets/img/'
}
}
]
}
]
},
plugins: [
// plugins
]
};
Node server start point is ./server.js
React client start point is ./src/index.js
Output path ./public contain index.html with lines:
<div id="root"></div>
<script type="text/javascript" src="/js/bundle.js" charset="utf-8"></script>
Output path for bundle.js is ./public/js
Output path for fonts is ./public/assets/fonts
Output path for images is ./public/assets/img
Start: npm run dev (listening port is defined in server.js)
etc.
I don't know if this would help, but i think that you want do the other way round:
Create your configuration un Webpack.config file (Webpack).
Your webpack file lauch the Node server (Express).
Your server return your font-end file (React).
You can learn some info about webpack in this post.
Try this. Save this code in webpackConfig.js
var webpack = require('webpack')
var config = require('./your_config')
var compiler = webpack(config)
compiler.run(function(err, stats){
console.log(err, stats)
})
run with "node webpackConfig.js"

React Webpack production setup

I'm trying to put my ReactJS website into production. However, I believe that my setup with my server and webpack is not well made so that it fails to load the built CSS and js on Heroku. Can anyone check on my setup, please?
server.js:
const path = require('path');
const express = require('express');
const compression = require('compression');
const minify = require('express-minify');
const webpack = require('webpack');
const webpackMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const config = require('./webpack.config.js');
const app = express();
/** *************************** Environment Setup ************************** **/
const isDeveloping = process.env.NODE_ENV !== 'production';
const port = isDeveloping ? 2333 : process.env.PORT;
/** ****************************** Output Setup **************************** **/
if (isDeveloping) {
const compiler = webpack(config);
const middleware = webpackMiddleware(compiler, {
publicPath: config.output.publicPath,
contentBase: 'src',
stats: {
colors: true,
hash: false,
timings: true,
chunks: false,
chunkModules: false,
modules: false
}
});
app.use(middleware);
// Compress everything to speedup
app.use(compression({threshold: 0}));
// Minify and cache everything
app.use(minify());
app.use(webpackHotMiddleware(compiler));
app.get('*', function response(req, res) {
res.sendFile(path.join(__dirname, '/dist'));
res.end();
});
} else {
// Compress everything to speedup
app.use(compression({threshold: 0}));
// Minify and cache everything
app.use(minify());
app.use(express.static(__dirname + '/dist'));
app.get('*', function response(req, res) {
res.sendFile(path.join(__dirname, '/dist'));
});
}
/** **************************** Server Running **************************** **/
app.listen(port, '0.0.0.0', function onStart(err) {
if (err) {
console.log(err);
}
console.info('==> 🌎 Listening on port %s.', port);
});
webpack.production.config.js:
'use strict';
var path = require('path');
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var StatsPlugin = require('stats-webpack-plugin');
module.exports = {
entry: [
path.join(__dirname, 'app/App.jsx')
],
output: {
path: path.join(__dirname, 'dist'),
filename: '[name]-[hash].min.js',
publicPath: '/dist/'
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new HtmlWebpackPlugin({
template: 'app/index.tpl.html',
inject: 'body',
filename: 'index.html'
}),
new ExtractTextPlugin('[name]-[hash].min.css'),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compressor: {
warnings: false,
screw_ie8: true
}
}),
new StatsPlugin('webpack.stats.json', {
source: false,
modules: false
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
],
resolve: {
root: path.resolve('./'),
alias: {
jsx: 'app/jsx',
components: 'app/jsx/components',
utils: 'app/jsx/utils'
},
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
query: {
"presets": ["es2015", "stage-0", "react"]
}
}, {
test: /\.json?$/,
loader: 'json'
}, {
test: /\.css$/,
loader: ExtractTextPlugin.extract('style', 'css?modules&localIdentName=[name]---[local]---[hash:base64:5]!postcss')
}, {
test: /img.*\.(jpg|jpeg|gif|png|svg)$/i,
loader: 'url-loader?name=/app/img/[name].[ext]'
}, {
test: /\.ico$/,
loader: 'file-loader?name=app/img/[name].[ext]'
}]
},
postcss: [
require('autoprefixer')
]
};
package.json script:
...
"scripts": {
"test": "",
"start": "node server",
"build": "rimraf dist && cross-env NODE_ENV=production webpack --config ./webpack.production.config.js --progress --profile --colors",
"eslint": "eslint .",
"jscs": "jscs .",
"prod": "NODE_ENV=production node server",
"postinstall": "npm run build"
},
...
Thanks for the help.

Resources