Recently, one of my clients wants to generate node.js production build that includes node_modules so he doesn't need to run npm install on every server. Also he can distribute same build to his N number of customers servers. As this is deployed on multiple VM there is config.js file which will be going to read run time upon node server start. So I also need to consider that run time config as a part of bundle.
In this article I will show you how can you generate Node.js production build using webpack 4.
When I started I found few articles but none of them has clear answer about how can I include config.js file as run time require file.
Here is my most updated webpack.prod.config file for your reference.
const path = require('path');
const webpack = require('webpack');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const CopyWebpackPlugin = require('copy-webpack-plugin')
module.exports = {
entry: {
app: './src/index.js'
},
plugins: [
new CleanWebpackPlugin(['dist']),
new webpack.IgnorePlugin(/vertx/),
new CopyWebpackPlugin([
{ from: './src/config.js' }
])
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
target: 'node',
externals: [nodeExternals()],
module: {
exprContextCritical: false
}
};
This config will basically generate bundle.js and will also copy config.js file into build directory using CopyWebpackPlugin. For config.js to be referred run time I have to make following changes in my code.
let config;
if(process.env.NODE_ENV === 'production'){
config = __non_webpack_require__("./config.js");
} else {
config = require('./config');
}
export default config;
__non_webpack_require__
will basically used to tell webpack to ignore
that
require to be transpile. Now whenever I run bundle.js it will include config.js from the current
directory as module dependency. Bundle is so clean that client does not need to run npm install
command
everytime.
What's Next?
if you have similar requirement or new requirement then you can contact us at hello@3braintechnologies.com OR call us on +918866133870.
Hire Node.js Developers