When creating minified and unminified bundles with Webpack, we can achieve this by configuring the webpack configuration file. Here are the specific steps and examples:
1. Install Required Dependencies
First, ensure that Node.js and npm are installed. Then, in the project directory, install webpack and webpack-cli:
bashnpm install --save-dev webpack webpack-cli
2. Basic Configuration File
Create a file named webpack.config.js in the root directory of your project; this will be the webpack configuration file. We need to export a configuration object:
javascriptconst path = require('path'); module.exports = { entry: './src/index.js', // Entry file output: { filename: 'bundle.js', // Output filename path: path.resolve(__dirname, 'dist'), // Output path }, mode: 'none', // Default: no optimization options enabled };
3. Set Multiple Modes
To generate both minified and unminified bundles simultaneously, control the build mode using environment variables. Modify the webpack.config.js file to add support for environment variables:
javascriptmodule.exports = (env) => { return { entry: './src/index.js', output: { filename: env.production ? 'bundle.min.js' : 'bundle.js', path: path.resolve(__dirname, 'dist'), }, mode: env.production ? 'production' : 'development', }; };
4. Modify package.json Scripts
In the package.json file, add two scripts to build both minified and unminified versions:
json"scripts": { "build": "webpack --env.production", "dev": "webpack --env.development" }
5. Run the Build
- Running
npm run devwill generate the unminifiedbundle.js. - Running
npm run buildwill generate the minifiedbundle.min.js.
Example Explanation
In this configuration:
- When
mode: 'production'is set, it automatically enables minification (using plugins like TerserPlugin). - When
mode: 'development'is set, it provides source map support and does not minify the code, facilitating debugging. env.productionandenv.developmentare environment variables passed via scripts, informing webpack which mode to use.
With this setup, you can flexibly control the output files and minification level, which is ideal for different requirements in development and production environments.