代码之家  ›  专栏  ›  技术社区  ›  Zhengquan Bai

Web包4中的babel loader无法使用树抖动

  •  1
  • Zhengquan Bai  · 技术社区  · 6 年前

    我正在修改网页文档中的摇树示例。但似乎一旦我加入巴别塔加载器,摇树就不起作用了。 以下是我的项目概述:

    指数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"
      }
    }

    网页包。配置。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'
    		})
    	]
    };

    作为索引。js没有使用square函数,square函数应该从捆绑包中删除。然而,当我打开包裹时。搜索“square”,我仍然可以找到square函数和控制台日志语句。在我在webpack config中注释掉babel loader规范并再次运行npm构建之后,在生成的bundle文件中找不到“square”这个词。

    我确实指定了 模块:false 在里面巴别LRC。
    有人能告诉我是什么导致了这个问题吗?
    以下是用于复制的回购协议: https://github.com/blogrocks/treeshaking-issue.git

    2 回复  |  直到 6 年前
        1
  •  2
  •   Zhengquan Bai    6 年前

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

    哦,我终于发现是react hot loader从命令中键入了NODE\u ENV=production!!

        2
  •  -1
  •   alx    6 年前

    在我的情况下,为了使树震动工作,我还必须显式设置NODE\u ENV:

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