如何消除死的 webpack 需要/导入? [英] How to eliminate dead webpack requires/imports?
问题描述
我想根据环境(开发/生产)使用 Webpack (v2.5.1) 和 UglifyJsPlugin 删除某些文件要求/导入.
I want to remove certain file require/imports depending on the environment (development/production) using Webpack (v2.5.1) and UglifyJsPlugin.
现状
export const IMAGES = Object.assign(
{
PROFILE: require('images/profile.png'),
// ...
},
process.env.NODE_ENV !== 'production' && {'LOGO': require('images/logo.png')}
);
到目前为止,在生产构建之后,输出的 Javascript 文件不包含 IMAGES.LOGO
键,而是所需的 images/logo.png
文件存在于输出中.
I have gotten so far that after the production build the outputted Javascript file doesn't contain an IMAGES.LOGO
key, but the required images/logo.png
file is present in the output.
我有一种预感,Webpack 在 Uglify 之前解析文件,然后保留它们,尽管它们在消除死代码后不再使用.
I have a hunch that Webpack resolves the files before Uglify and afterwards keeps them, although they aren't used anywhere anymore after dead code elimination.
有没有办法实现它?
Webpack 插件配置
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('production')
}),
new webpack.optimize.UglifyJsPlugin({
comments: false,
sourceMap: true
})
推荐答案
通过发布到 Webpack GitHub 存储库,了解到死代码消除在此示例中不起作用.如果我使用 if
子句更直接地重写它,它会起作用,如下所示:
By issue to Webpack GitHub repo, understood that the dead-code elimination doesn't work in this example. It works if I rewrite it more straightforward with an if
clause, as follows:
export const IMAGES = {
PROFILE: require('images/profile.png'),
// ...
};
if (process.env.NODE_ENV !== 'production') {
IMAGES.LOGO = require('images/logo.png');
}
这篇关于如何消除死的 webpack 需要/导入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!