如何区分开发和上线的环境呢?如果开发用一套配置,上线前再修改,那么难免出错,而且也很麻烦。好在webpack提供了一个插件(DefinePlugin),帮助我们注入一个变量,方便我们区分开发和线上环境
//webpack.config.js
plugins: [
....
new webpack.DefinePlugin({
'DEV': JSON.stringify('dev'), //相当于 "'dev'",
'FLAG': 'true' // 同理,取值时,会默认去掉引号,即为布尔值true
})
]
//index.js
let url = "";
if (DEV === "dev") {
url = "http://localhost:8000";
} else {
url = "http://www.baidu.com";
}
console.log(url); // http://localhost:8000
以上,就可以区分不同环境,但是,每次都需要修改DefinePlugin,我们可以分别定义开发和生产的配置文件来达到二者完全分离的效果。具体怎么做呢?
两个配置文件公共的部分,可以抽离出一个公共的配置文件webpack.base.js,再分别定义webpack.dev.js和webpack.prod.js,在做这些之前需要安装一个插件来桥接base和它们,“webpack-merge”
webpack.base.js中就定义那些公共的配置,此处不再赘述。
// webpack.prod.js
let { smart } = require("webpack-merge");
let base = require("./webpack.base.js");
let webpack = require("webpack");
module.exports = {
mode: "production",
plugins: [
new webpack.DefinePlugin({
DEV: JSON.stringify('production');
})
]
};
// webpack.dev.js
let { smart } = require("webpack-merge");
let base = require("./webpack.base.js");
let webpack = require("webpack");
module.exports = {
mode: "development",
devServer: {
...
},
devtools: 'eval-source-map',
plugins: [
new webpack.DefinePlugin({
DEV: JSON.stringify("dev")
})
]
};
网友评论