简体   繁体   English

避免从导入导入中提取代码

[英]Avoid bringing code from imports of imports

I'm going through the exercise of making my webpack bundle smaller, and using webpack's bundle analyzer I saw that a really heavy package is being included in two different async chunks, even though it's only used once. 我正在练习使我的webpack包更小,并且使用webpack的bundle分析器,我看到一个非常重的包被包含在两个不同的异步块中,即使它只使用一次。 After some digging in my code, I've come to realize that it is probably because of the following scenario: 在对我的代码进行一些挖掘之后,我逐渐意识到这可能是由于以下情况:

file1.js file1.js

import { foo } from 'ReallyHeavyPackage'

export function a(): string {
    console.log("called a()");
}

export function b(): string {
    return foo();
}

file2.js file2.js

import { a } from './file1.js'

a();

file3.js file3.js

import { b } from './file1.js'

b();

I'm assuming that since file1 imports the heavy package globally, and file2 imports a function from file1, it gets the heavy package as a dependency, even though it doesn't import the function that is actually using the package. 我假设由于file1全局导入重包,而file2从file1导入一个函数,它将重包作为依赖,即使它没有导入实际使用该包的函数。 I'd expect (or rather, wish) that only the chunk for file3 has the heavy dependency included, since it's the only place where it is being used. 我希望(或者更确切地说,希望)只有file3的块具有重依赖性,因为它是唯一使用它的地方。

Is there a specific way I should be handling an import like this? 有没有一种特定的方式我应该处理像这样的导入? Perhaps a magic configuration I can do in webpack to help with this, a better way of structuring the modules/functions or just better way to import functions/modules/packages? 也许我可以在webpack中做一个神奇的配置来帮助解决这个问题,一个更好的方法来构建模块/函数或者更好的方法来导入函数/模块/包?

I'm using webpack 4 and I'm on ES2017 我正在使用webpack 4而我正在使用ES2017

Maybe try dynamic imports? 也许尝试动态导入?

export function a(): string {
  console.log("called a()");
}

export async function b(): string {
  const { foo } = await import('ReallyHeavyPackage');
  return foo();
}

https://webpack.js.org/guides/code-splitting/#dynamic-imports https://webpack.js.org/guides/code-splitting/#dynamic-imports

I think what you're looking for is the Webpack CommonChunksPlugin : https://webpack.js.org/plugins/commons-chunk-plugin/ . 我认为您正在寻找的是Webpack CommonChunksPluginhttpsCommonChunksPlugin This plugin takes common chunks (modules/libraries) from different bundles and puts them into their own bundle. 这个插件从不同的bundle中获取常见的块(模块/库),并将它们放入自己的bundle中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM