乐闻世界logo
搜索文章和话题

How to build minified and uncompressed bundle with webpack?

1个答案

1

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:

bash
npm 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:

javascript
const 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:

javascript
module.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 dev will generate the unminified bundle.js.
  • Running npm run build will generate the minified bundle.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.production and env.development are 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.

2024年11月2日 22:18 回复

你的答案