编写两个不同的配置文件,开发和生成时,分别加载不同的配置文件即可。在不同的配置文件中使用变量来说明环境,也可以通过配置脚本带上–env production来表明开发环境,这样就可以在webpack.config.js中导出的函数中通过参数判断环境,当然最终返回的还是对象。
"scripts": {
"build": "webpack --config ./config/webpack.prod.js --env production",
"serve": "webpack serve --config ./config/webpack.dev.js --env development"
}
先设置process.env.NODE_ENV,然后通过process.env.NODE_ENV获取当前的环境是生产环境还是开发环境。
编写webpack.dev.js和webpack.prod.js及webpack.common.js。然后通过使用merge进行合并。注意babel的配置文件,由于需要判断环境,所以我们在webpack.common.js进行process.env.NODE_ENV的挂载,在babel.config.js拿到进行判断不同环境,babel不同的配置。
const resolveApp = require("./paths");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
const { merge } = require("webpack-merge");
const prodConfig = require("./webpack.prod");
const devConfig = require("./webpack.dev");
const commonConfig = {
entry: "./src/index.js",
output: {
filename: "bundle.js",
path: resolveApp("./build"),
},
resolve: {
extensions: [".wasm", ".mjs", ".js", ".json", ".jsx", ".ts", ".vue"],
alias: {
"@": resolveApp("./src"),
pages: resolveApp("./src/pages"),
},
},
module: {
rules: [
{
test: /\.jsx?$/i,
use: "babel-loader",
},
{
test: /\.vue$/i,
use: "vue-loader",
},
{
test: /\.css/i,
use: ["style-loader", "css-loader"],
},
],
},
plugins: [
new HtmlWebpackPlugin({
template: "./index.html",
}),
new VueLoaderPlugin(),
]
};
module.exports = function(env) {
const isProduction = env.production;
process.env.NODE_ENV = isProduction ? "production": "development";
const config = isProduction ? prodConfig : devConfig;
const mergeConfig = merge(commonConfig, config);
return mergeConfig;
};
const resolveApp = require('./paths');
const ReactRefreshWebpackPlugin = require('@pmmmwh/react-refresh-webpack-plugin');
const isProduction = false;
console.log("加载devConfig配置文件");
module.exports = {
mode: "development",
devServer: {
hot: true,
hotOnly: true,
compress: true,
contentBase: resolveApp("./why"),
watchContentBase: true,
proxy: {
"/why": {
target: "http://localhost:8888",
pathRewrite: {
"^/why": ""
},
secure: false,
changeOrigin: true
}
},
historyApiFallback: {
rewrites: [
{from: /abc/, to: "/index.html"}
]
}
},
plugins: [
// 开发环境
new ReactRefreshWebpackPlugin(),
]
}
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const isProduction = true;
module.exports = {
mode: "production",
plugins: [
// 生成环境
new CleanWebpackPlugin({}),
]
}