1

我正在修改 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());

数学.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"]
}

包.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 函数,因此应该将 square 函数从包中删除。但是,当我打开 bundle.js 并搜索“square”时,我仍然可以找到 square 函数和控制台日志语句。在我注释掉 webpack config 中的 babel-loader 规范并再次 npm run build 之后,在生成的包文件中看不到“square”字样。

我确实在 .babelrc中指定了模块:false 。
谁能告诉我是什么导致了这个问题?
这是用于复制的存储库: https ://github.com/blogrocks/treeshaking-issue.git

4

2 回答 2

3

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

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

于 2018-04-14T13:43:04.610 回答
0

在我的情况下,要使摇树工作,我还必须明确设置 NODE_ENV:

"scripts": {
    "build": "cross-env NODE_ENV=production webpack --config webpack.prod.js"
}
于 2018-10-21T13:17:59.187 回答