摇树不适用于 webpack 4 中的 babel loader

Tree shaking doesn't work with babel loader in webpack 4

我正在修改 webpack 文档中的 tree shaking 示例。但是,一旦我将 babel-loader 添加到组合中,tree shaking 似乎就不起作用了。 这是我的项目的概述:

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 不使用平方函数,平方函数应该被 p运行 从包中删除。但是,当我打开 bundle.js 并搜索 'square' 时,我仍然可以找到平方函数和控制台日志语句。我在 webpack config 中注释掉 babel-loader 规范并再次 npm 运行 build 后,生成的 bundle 文件中找不到 "square" 字样

我确实在 .babelrc.
中指定了 modules: false 谁能告诉我是什么导致了这个问题?
这是复制的回购协议: https://github.com/blogrocks/treeshaking-issue.git

我的问题终于解决了。我应该在 运行 webpack 时指定 "cross-env NODE_ENV=production"。甚至在插件中使用 DefinePlugin 将 NODE_ENV 设置为 "production" 还不够。似乎 babel-loader 从命令中关闭了 "NODE_ENV=production"。

哦,我终于发现是 react-hot-loader 从命令中关闭 NODE_ENV=production!!

在我的例子中,为了使 tree shaking 工作,我还必须明确设置 NODE_ENV:

"scripts": {
    "build": "cross-env NODE_ENV=production webpack --config webpack.prod.js"
}