我正在修改webpack文档中的树摇动示例。但是,一旦我将babel-loader添加到混音中,看起来树摇动并不起作用。
以下是我的项目概述:
index.js:
import { cube } from "./math";
function component() {
const element = document.createElement('pre');
element.innerHTML = [
'Hello webpack!',
'5 cubed is equal to ' + cube(5)
].join('\n\n');
return element;
}
document.body.appendChild(component());

math.js:
export function square(x) {
console.log('square');
return x * x;
}
export function cube(x) {
console.log('cube');
return x * x * x;
}

.babelrc:
{
"presets": [
["env", { "modules": false }],
"react"
],
"plugins": ["react-hot-loader/babel"]
}

的package.json:
{
"dependencies": {
"react": "^16.3.1",
"react-dom": "^16.3.1",
"react-hot-loader": "^4.0.1"
},
"name": "react-webpack-starter",
"version": "1.0.0",
"main": "index.js",
"license": "MIT",
"scripts": {
"start": "webpack-dev-server --mode development --open --hot",
"build": "webpack -p --optimize-minimize"
},
"sideEffects": false,
"devDependencies": {
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-preset-env": "^1.6.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^3.2.0",
"webpack": "^4.5.0",
"webpack-cli": "^2.0.14",
"webpack-dev-server": "^3.1.3"
}
}

webpack.config.js:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
path: path.join(__dirname, '/dist'),
filename: 'index_bundle.js'
},
mode: 'production',
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html'
})
]
};

由于index.js不使用square函数,因此应该从bundle中删除square函数。但是,当我打开bundle.js并搜索' square'时,我仍然可以找到square函数和console log语句。在我注释掉webpack配置中的babel-loader规范并再次运行npm后," square"在生成的包文件中无处可见单词。
我确实在.babelrc中指定了 modules:false
谁能告诉我可能导致这个问题的原因是什么?
这是复制的回购:
https://github.com/blogrocks/treeshaking-issue.git
答案 0 :(得分:2)
我的问题终于得到了解决。我应该在运行webpack时指定“cross-env NODE_ENV = production”。并且甚至不足以使用DefinePlugin将NODE_ENV设置为插件中的“生产”。似乎babel-loader从命令中关闭了“NODE_ENV = production”。
哦,我终于发现反应热门加载器正在从命令中关闭NODE_ENV =生产!!
答案 1 :(得分:0)
要使摇树工作,我还必须显式设置NODE_ENV:
"scripts": {
"build": "cross-env NODE_ENV=production webpack --config webpack.prod.js"
}