为什么 webpack 在使用“import * as _"时不摇树 lodash? [英] Why webpack doesn't tree-shake the lodash when using "import * as _"?

查看:51
本文介绍了为什么 webpack 在使用“import * as _"时不摇树 lodash?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个使用 Lodash 的 webpack 4/React 应用程序学习摇树.

I am learning about tree-shaking with a webpack 4/React application that uses Lodash.

起初,我的 Lodash 用法是这样的:

At first, my Lodash usage looked like this:

import * as _ from "lodash";
_.random(...

我很快通过 BundleAnalyzerPlugin 了解到,整个 Lodash 都包含在开发和生产版本中 (527MB).

I soon learned, via the BundleAnalyzerPlugin, that the entirety of Lodash was being included in both dev and prod builds (527MB).

谷歌搜索之后我意识到我需要使用特定的语法:

After googling around I realized that I needed to use a specific syntax:

import random from "lodash/random";
random(...

现在,只有 random 和它的依赖项正确地包含在包中,但我还是有点困惑.

Now, only random and it's dependencies are correctly included in the bundle, but I'm still a little confused.

如果我需要在我的 import 语句中明确指定函数,那么 tree-shaking 实际扮演了什么角色?在比较开发模式和生产模式构建时,BundleAnalyzerPlugin 没有显示有效负载大小的差异(两者都是正确的小尺寸,但我认为摇树仅发生在生产构建中?).

If I need to explicitly specify functions in my import statement, then what role is the tree-shaking actually playing? The BundleAnalyzerPlugin isn't showing a difference in payload size when comparing between dev and production mode builds (it's the correct small size in both, but I thought that tree-shaking only took place with production builds?).

我的印象是 TreeShaking 会执行某种静态代码分析,以确定实际使用了代码的哪些部分(可能基于功能?)并剪掉未使用的位.

I was under the impression that TreeShaking would perform some sort of static code analysis to determine which parts of the code were actually being used (perhaps based on function?) and clip off the unused bits.

为什么我们不能总是只在我们的 import 中使用 * 并依靠 TreeShaking 找出实际包含在包中的内容?

Why can't we always just use * in our import and rely on TreeShaking to figure out what to actually include in the bundle?

如果有帮助,这是我的webpack.config.js:

In case it helps, here is my webpack.config.js:

const path = require("path");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer").BundleAnalyzerPlugin;

module.exports = {
  entry: {
    app: ["babel-polyfill", "./src/index.js"]
  },
  plugins: [
    new BundleAnalyzerPlugin({
      analyzerMode: "static",
      openAnalyzer: false
    })
  ],
  devtool: "source-map",
  output: {
    filename: "[name].js",
    path: path.resolve(__dirname, "dist"),
    chunkFilename: "[name].bundle.js",
    publicPath: ""
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        loader: "babel-loader",
        include: /src/,
        options: {
          babelrc: false,
          presets: [
            [
              "env",
              {
                targets: {
                  browsers: ["last 2 Chrome versions"]
                }
              }
            ],
            "@babel/preset-env",
            "@babel/preset-react"
          ],
          plugins: ["syntax-dynamic-import"]
        }
      },
      {
        test: /\.(ts|tsx)$/,
        use: [
          {
            loader: require.resolve("ts-loader"),
            options: {
              compiler: require.resolve("typescript")
            }
          }
        ]
      }
    ]
  },
  resolve: {
    symlinks: false,
    extensions: [".js", ".ts", ".tsx"],
    alias: {
      react: path.resolve("./node_modules/react")
    }
  }
};

我正在使用 webpack --mode=developmentwebpack --mode=production 调用 webpack.

I'm invoking webpack with webpack --mode=development and webpack --mode=production.

推荐答案

所有两个现有答案都是错误的,webpack do treeshake import *,但是只有在使用 esmodule 时才会发生这种情况,而 lodash 则不会.正确的解决方法是使用 lodash-es

All two existing answers are wrong, webpack do treeshake import *, however that only happens when you're using a esmodule, while lodash is not. The correct solution is to use lodash-es

这个答案只适用于 webpack4,而 webpack 5 支持 commonjs 的树抖动的有限子集,但我没有自己测试过

this answer only applies to webpack4, while webpack 5 supported a limited subset of tree shaking for commonjs, but I haven't tested it myself

这篇关于为什么 webpack 在使用“import * as _"时不摇树 lodash?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆