这个插件是用来定义全局变量的
//webpack.config.js
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: {
index: "./js/index.js"
},
output: {
path: "./dist/",
filename: "js/[name].js",
chunkFilename: "js/[name].js"
},
plugins: [
new webpack.DefinePlugin({
SOMETHINE: 'This is something we needed.'
})
]
};
//index.js
console.log('SOMETHINE=',SOMETHINE);
编译完结果如下:
可以看到代码中 SOMETHINE 被直接替换为 This is something we needed. 但是我们的本意中 SOMETHINE 是一个字符串,而直接替换后却不是一个字符串。
如何换成字符串
SOMETHINE: '"This is something we needed."'
//or借助JSON.stringify
SOMETHINE: JSON.stringify('This is something we needed.')
借助JSON.stringify不仅可以处理字符串,还可以处理Object中的字符串和Array
//webpack.config.js
plugins: [
new webpack.DefinePlugin({
OBJ: JSON.stringify({"key1": "this is value"}),
OBJ2: {"key1": "this is value"},
OBJ3: {"key1": "'this is value'"},
ARRAY: JSON.stringify(["value1", "value2"]),
ARRAY2: ["value1", "value2"],
ARRAY3: ["'value1'", "'value2'"],
// Number 和 Boolean 两种变量类型
NUMBER: 12,
BOOL: true
})
]
//index.js
console.log('OBJ=', OBJ);// OBJ= { key1: 'this is value' }
console.log('OBJ2=', OBJ2);//报错 console.log('OBJ2=', Object({"key1":this is value}));
console.log('OBJ3=', OBJ3);// OBJ3= { key1: 'this is value' }
console.log('ARRAY=', ARRAY);// ARRAY= [ 'value1', 'value2' ]
console.log('ARRAY2=', ARRAY2);// ARRAY2= {"0":value1,"1":value2} value1 is not defined
console.log('ARRAY3=', ARRAY3);// ARRAY3= { '0': 'value1', '1': 'value2' }
console.log(NUMBER,BOOL);// 12 true
实际应用
在实际使用中, DefinePlugin 最为常用的用途就是用来处理我们开发环境和生产环境的不同。
比如一些 debug 的功能在生产环境中需要关闭、开发环境中和生产环境中 api 地址的不同。
// webpack.dev.conf.js
var config = require('../config')
...
new webpack.DefinePlugin({
'process.env': config.dev.env
})
// webpack.prod.conf.js
var config = require('../config')
...
new webpack.DefinePlugin({
'process.env': config.build.env
})
// index.js
if ('development' === process.env.NODE_ENV) {
// 开发环境下的逻辑
} else {
// 生产环境下
}