[Webpack] Create Separate webpack Configs for Development and Production with webpack-merge

本文介绍如何将Webpack配置分为开发和生产模式,通过使用webpack-merge插件,创建base、dev和prod三个配置文件,分别针对不同环境进行优化,以实现更好的开发者体验和用户性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

The development and production modes in webpack optimize the output in different ways. In development mode, the focus is on faster builds and a better developer experience. In production mode, the focus is on highly optimized bundles, leading to a better user experience. The good news is, we can have both. In this lesson, we'll separate our webpackconfig into two configurations and update our scripts to run the right config for our needs.

 

Install:

npm i -D webpack-merge

 

Create a webpack.config.base.jf:

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'app.bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        options: {
          presets: ['@babel/preset-env', '@babel/preset-react']
        }
      }
    ]
  },
  plugins: [new HtmlWebpackPlugin({
    template: './src/index.html'
  })]
}

 

webpack.config.dev.js:

const merge = require('webpack-merge')
const baseConfig = require('./webpack.config.base')

module.exports = merge(baseConfig, {
  mode: 'development'
})

 

webpack.config.prod.js:

const merge = require('webpack-merge')
const baseConfig = require('./webpack.config.base')

module.exports = merge(baseConfig, {
  mode: 'production'
})

 

Update scripts to adopt changes:

"scripts": {
    "build": "webpack --config webpack.config.prod.js",
    "dev": "webpack --watch --config webpack.config.dev.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  }

 

转载于:https://www.cnblogs.com/Answer1215/p/10386308.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值