为了在您的 webpack.config.js 中区分开发环境和生产环境构建,您可以使用环境变量。
webpack 命令行环境选项 --env 允许您传入任意数量的环境变量。环境变量将在您的 webpack.config.js 中可用。例如,--env production 或 --env goal=local。
npx webpack --env goal=local --env production --progress
您需要对 webpack 配置进行一项更改。通常,module.exports 指向配置对象。要使用 env 变量,您必须将 module.exports 转换为一个函数。
webpack.config.js
const path = require('path');
module.exports = (env) => {
// Use env.<YOUR VARIABLE> here:
console.log('Goal: ', env.goal); // 'local'
console.log('Production: ', env.production); // true
return {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
};