# DefinePlugin - webpack 变量
# 1. 介绍
编译期,将变量替换为指定的值或表达式。
常用于指定不同环境(development、production)的变量的值
# 2. 示例
webpack.config.js:
const { DefinePlugin } = require('webpack');
module.exports = {
plugins: [
new DefinePlugin({
__IS_DEV__: false,
__TOTAL__: 100,
'process.env.BASE_URL': JSON.stringify('http://localhost:8080'),
}),
],
};
src/index.js:(源码)
// 业务代码
console.log('__IS_DEV__', __IS_DEV__);
console.log('__TOTAL__', __TOTAL__);
console.log('process.env.BASE_URL', process.env.BASE_URL);
// 库开发
// 在库源文件,可以通过 process.env.xxx 来指定一些开关变量,
// 库的使用者,可以通过 DefinePlugin 来给开关变量赋值。
if (process.env.__FEATURE_HTTP__) {
console.log('enable http feature');
}
if (process.env.__FEATURE_PROXY__) {
console.log('enable proxy feature');
}
dist/index.js:(编译后)
console.log("__IS_DEV__",!1),
console.log("__TOTAL__",100),
console.log("process.env.BASE_URL","http://localhost:8080"),
process.env.__FEATURE_HTTP__&&console.log("enable http feature"),
process.env.__FEATURE_PROXY__&&console.log("enable proxy feature");
# 3. 参考
上一篇: 下一篇:
本章目录