Speed up NodeJS server-side development with Webpack 4 + HMR

Structure and Logic:

require('babel-core/register');
require('babel-polyfill');
global.Promise = require("bluebird");
require('./server.js');
import express from "express"const PORT = process.env.PORT || 3000;
const app = express();
/*
set up all your server config here
*/
server.listen(PORT, function () {
console.log('Server listening on', PORT);
});

The idea

Implementation

const webpack = require('webpack');
const path = require('path');
const nodeExternals = require('webpack-node-externals');
const nodeEnv = process.env.NODE_ENV;
const isProduction = nodeEnv !== 'development';
// Common plugins
let plugins = [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(nodeEnv),
},
}),
new webpack.NamedModulesPlugin()
];
if (!isProduction) {
plugins.push(new webpack.HotModuleReplacementPlugin())
}
const entry = isProduction ? [
'babel-polyfill',
path.resolve(path.join(__dirname, './server.js'))
] : [
'webpack/hot/poll?1000',
'babel-polyfill',
path.resolve(path.join(__dirname, './server.js'))
];
module.exports = {
mode: 'development',
devtool: false,
externals: [
nodeExternals()
],
name : 'server',
plugins: plugins,
target: 'node',
entry: entry,
output: {
publicPath: './',
path: path.resolve(__dirname, './'),
filename: 'server.prod.js',
libraryTarget: "commonjs2"
},
resolve: {
extensions: ['.webpack-loader.js', '.web-loader.js', '.loader.js', '.js', '.jsx'],
modules: [
path.resolve(__dirname, 'node_modules')
]
},
module : {
rules: [
{
test: /\.(js|jsx)$/,
loader: "babel-loader",
options : {
babelrc : true
}
}
],
},
node: {
console: false,
global: false,
process: false,
Buffer: false,
__filename: false,
__dirname: false,
}
};
node: {
console: false,
global: false,
process: false,
Buffer: false,
__filename: false,
__dirname: false,
}
const entry = isProduction ? [
'babel-polyfill',
path.resolve(path.join(__dirname, './server.js'))
] : [
'webpack/hot/poll?1000',
'babel-polyfill',
path.resolve(path.join(__dirname, './server.js'))
];

Running the scripts

"scripts": {
"build:server:once": "cross-env NODE_ENV=development webpack --config webpack.config.server.js",
"dev:server": "npm run build:server:once && npm-run-all --parallel nodemon:prod watch:server",
"watch:server": "cross-env NODE_ENV=development webpack --config webpack.config.server.js --watch",
"nodemon:prod": "cross-env NODE_ENV=development node-dev server.prod.js"
},

Why is it so much faster?

Results

Caveats

Software Architect, currently @ Vodafone GR. Past: Lead Dev @ Intrasoft Intl, atcom.gr and more. Crafting apps & web services since 2007. https://oramind.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store