The npm module webpack-merge is a confortable way of having multiple configuration files in webpack. It allows to have a common configuration file and several other that "extend" from this one as the following example will show.
Installing
npm install webpack-merge
Common webpack config file
This would be where the common configurations between your other files are.
webpack.common.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports = {
entry: "./src/index.js",
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({
title: "Output Management",
template: "src/index.html",
}),
],
output: {
filename: "bundle.js",
path: path.resolve(__dirname, "dist"),
},
};
Extending files
I decided to use development and production configuration files for the example but any amount can be used.
webpack.dev.js
const path = require("path");
const { merge } = require("webpack-merge");
const common = require("./webpack.common.js");
module.exports = merge(common, {
mode: "development",
devServer: {
contentBase: path.join(__dirname, "dist"),
compress: true,
port: 9000,
},
});
webpack.prod.js
const { merge } = require("webpack-merge");
const common = require("./webpack.common.js");
module.exports = merge(common, {
mode: "production",
});
In both you import the merge function and use it to create your files without having to duplicate code. In your scripts you can simply call the extending configuration files like so.
package.json
...
"scripts": {
"build": "webpack --config webpack.prod.js",
"dev": "webpack serve --config webpack.dev.js"
},
...