webapck defineplugin 为何要这样用?
发布于 9 年前 作者 Alexis374 13001 次浏览 来自 问答

如这篇文章所说,

new webpack.DefinePlugin({
 "process.env": {
 NODE_ENV: JSON.stringify("production") //而不是直接 'production'
 }
})

这个问题是我昨天在用webpack的时候发现的,如果直接使用 set NODE_ENV=production, 上面的配置不用JSON.stringify,就会在生成的代码里面直接把production当做一个变量,结果是production未定义而报错。。 后来搜索到这篇文章后改变了写法才生成了正确的代码

3 回复

plugins

DefinePlugin

new webpack.DefinePlugin({
 'process.env': {
 NODE_ENV: JSON.stringify(process.env.NODE_ENV)
 },
 TWO: '1 + 1',
 SOME_BOOLEAN: true
})
if(process.env.NODE_ENV !== 'production') {
 console.log('not in production')
}
console.log(process.env.NODE_ENV)
// TWO
console.log(TWO)
if(SOME_BOOLEAN) {
 console.log(SOME_BOOLEAN)
}
if (true) {
 console.log('not in production');
}
console.log(("development"));
// TWO
console.log((1 + 1));
if (true) {
 console.log((true));
}

看样子就是: 在 node 端, x = 'this_is_x', 就去将代码里面的 x 变量全部替换为 this_is_x

// before
x = 10
// after
this_is_x = 10

在 node 端, x = '"this_is_x"', 就去将代码里面的 x 变量全部替换为 "this_is_x"

// before
console.log(x);
// after
console.log("this_is_x");
回到顶部

AltStyle によって変換されたページ (->オリジナル) /