为什么使用“ import * as _”时,webpack不会摇晃lodash?

问题描述 投票:0回答:2

我正在学习使用Lodash的webpack 4 / React应用程序进行树状摇晃。

起初,我的Lodash用法看起来像这样:

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

[我很快通过BundleAnalyzerPlugin得知,Lodash的全部内容都包含在开发和生产版本中(527MB)。

googling around之后,我意识到我需要使用一种特定的语法:

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

现在,只有random及其依赖项正确包含在捆绑包中,但我仍然有些困惑。

如果我需要在import语句中明确指定函数,那么摇树实际上起着什么作用?在开发和生产模式构建之间进行比较时,BundleAnalyzerPlugin的有效负载大小没有差异(这都是正确的小尺寸,但我认为摇晃仅发生在生产构建中吗?)。

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

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

如果有帮助,这里是我的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。

我正在学习使用Lodash的webpack 4 / React应用程序进行树状摇动。一开始,我对Lodash的用法是这样的: _.random(...我很快就通过...

javascript webpack lodash tree-shaking es-module
2个回答
0
投票

我认为简短的解释是,摇树仅通过分析import语句而不是整个源代码来起作用。因此import *基本上告诉webpack导入所有导致更大尺寸的内容。


0
投票

实际上,它与Webpack的摇树能力无关。基于有关tree-shaking

© www.soinside.com 2019 - 2024. All rights reserved.