在实际开发项目时,webpack 生产环境和开发环境的打包有所不同,比如清除打包文件夹和复制文件只应该在生产环境打包时发挥作用。常常使用多配置文件来解决问题。
配置文件目录

// paths.jsconst path = require('path')const appDir = process.cwd()const resolveApp = (relativePath) => {return path.resolve(appDir, relativePath)}module.exports = resolveApp
通用配置文件
const resolveApp = require('./paths')const HtmlWebpackPlugin = require('html-webpack-plugin')const { merge } = require('webpack-merge')const ProdConfig = require('./webpack.prod')const DevConfig = require('./webpack.dev')const commonConfig = {entry: './src/index.js',output: {filename: 'js/main.js',path: resolveApp('./dist')},resolve: {extensions: ['.js', '.json', '.vue', '.jsx'],alias: {'@': resolveApp('./src')}},module: {rules: [{test: /\.css$/,use: ['style-loader',{loader: 'css-loader',options: {importLoaders: 1,esModule: false}},'postcss-loader']},{test: /\.less$/,use: ['style-loader','css-loader','postcss-loader','less-loader']},{test: /\.(png|svg|gif|jpe?g)$/,type: 'asset',generator: {filename: "img/[name].[hash:4][ext]"},parser: {dataUrlCondition: {maxSize: 30 * 1024}}},{test: /\.(ttf|woff2?)$/,type: 'asset/resource',generator: {filename: 'font/[name].[hash:3][ext]'}},{test: /\.jsx?$/,use: ['babel-loader']}]},plugins: [new HtmlWebpackPlugin({title: 'copyWebpackPlugin',template: './public/index.html'}),]}module.exports = (env) => {const isProduction = env.productionif (!isProduction) {process.env.NODE_ENV = isProduction ? 'production' : 'development'}const config = isProduction ? ProdConfig : DevConfigconst mergeConfig = merge(commonConfig, config)return mergeConfig}
生产环境配置文件
const CopyWebpackPlugin = require('copy-webpack-plugin')const { CleanWebpackPlugin } = require('clean-webpack-plugin')module.exports = {mode: 'production',plugins: [new CleanWebpackPlugin(),new CopyWebpackPlugin({patterns: [{from: 'public',globOptions: {ignore: ['**/index.html']}}]}),]}
开发环境配置文件
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin')module.exports = {mode: 'development',devtool: 'cheap-module-source-map',target: 'web',devServer: {// hot: true,hotOnly: true,open: false,port: 4000,compress: false,historyApiFallback: true,proxy: {'/api': {target: 'https://api.github.com',pathRewrite: { "^/api": "" },changeOrigin: true}}},plugins: [new ReactRefreshWebpackPlugin()]}
其他配置文件
其他配置文件如 babel 也要根据环境区分。
// babel.config.jsconst presets = [['@babel/preset-env'],['@babel/preset-react'],]const plugins = []if (process.env.NODE_ENV === 'development') { // 开发环境才需要使用这个插件plugins.push(['react-refresh/babel'])}module.exports = {presets,plugins}
命令行
多配置文件打包的命令需要加上 —env 参数。
"build2": "webpack --config ./config/webpack.common.js --env production","serve2": "webpack serve --config ./config/webpack.common.js --env development"
