动态导入被添加到 webpack 包中 [英] Dynamic import being added to webpack bundle

查看:26
本文介绍了动态导入被添加到 webpack 包中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在某个条件下导入一个模块,所以我通过动态导入语法来做:

I want to import a module under a certain condition, so I'm doing it through dynamic import syntax:

  if (showModal) {
    import('fancy-modal').then(({ initModal }) => {
      initModal();
    });
  }

这有效,但无论 showModal 的值是什么,它都会将fancy-modal"库代码添加到 webpack 包中.

This works but it adds the "fancy-modal" library code to the webpack bundle no matter what the value of showModal is.

我认为动态导入只会在条件为真时加载库,为什么 webpack 无论如何都会加载它?

I thought dynamic imports would only load the library if the condition is true, why is it being loaded by webpack no matter what?

推荐答案

Webpack 将始终构建您的所有代码,除非该变量保证始终为 false,例如当使用 define 插件并使用 if(process.env.NODE_ENV !== 'production'){//做一些仅用于开发的东西}.

Webpack will always build all of your code, unless the variable is guaranteed to always be false, e.g. when using a define plugin and using if(process.env.NODE_ENV !== 'production'){ // do some dev only stuff}.

默认情况下,webpack 4 将使用拆分块插件将动态导入拆分成块 https://webpack.js.org/plugins/split-chunks-plugin/

By default webpack 4 will split out dynamic imports into chunks using the split chunks plugin https://webpack.js.org/plugins/split-chunks-plugin/

如果您以非动态"方式在代码中的任何其他地方导入了 fancy-modal,webpack 会意识到这一点,并且只需在同一个包中构建一次,这样您就不会从动态导入中获得任何好处.

If you have imported fancy-modal anywhere else in your code in a "non dynamic" way, webpack will realise this and just build it once all in the same bundle, so you won't get any benefit from the dynamic import.

这篇关于动态导入被添加到 webpack 包中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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