Chunk generation logic of webpack

Time:2022-1-5

When you first come into contact with webpack, only a file called bundle will be generated after packaging with webpack. After getting familiar with webpack, if you have a certain understanding of front-end optimization, you will try to split the bloated bundle into multiple small files and load it on demand.

This paper hopes to explain some configurations of webpack, so that readers can have a certain understanding and mastery of relevant operations. The following operations are performed in [email protected] Description of the environment.

Configured in webpackoptimization.splitChunksTo achieve this effect, the configuration is alsoSplitChunksPluginsConfiguration of plug-ins.

Webpack isoptimization.splitChunksDefault values are provided. Let’s take a look at:

// 
//* * default splitchunks content**
//
{
  chunks: 'async',
  minSize: 30000,
  maxSize: 0,
  minChunks: 1,
  maxAsyncRequests: 5,
  maxInitialRequests: 3,
  automaticNameDelimiter: '~',
  automaticNameMaxLength: 30,
  name: true,
  cacheGroups: {
    vendors: {
      test: /[\\/]node_modules[\\/]/,
      priority: -10
    },
    default: {
      minChunks: 2,
      priority: -20,
      reuseExistingChunk: true
    }
  }
};

Let’s take a closer look at the configuration

chunks

By configuring this item, developers can select the chunks that need to be optimized. For the selected chunks, the modules will be analyzed and new chunks will be generated according to certain policies.

allowallasyncinitial(chunkname) => booleanFour values, the specific effects are as follows:

  • Initial: all immediately loaded chunks(e.g. bundle file)Will be checked
  • Async: all delayed loaded chunks will be checked
  • All: equivalent toinitial + asyncEffect, all chunks will be checked
  • (chunkname) = > Boolean: the function form can provide finer grained control

The default isasyncTherefore, our bundle will not be optimized. Here we can try to modify it toinitialThen compile again.

{
  chunks: 'initial',
}

In addition to generating the bundle, it may also be namedvendors~xxx.jsFile. (if it is not generated, you can try to introduce it into the codenode_modulesAnd then recompile to view the results.)

Changes in the results of two compilations, i.echunksfromasyncBecomeinitialAfter,Bundle fileIt is optimized as an immediately loaded chunk.

minSize、maxSize

See the name and know the meaning,minSizeandmaxSizeDefines the minimum / maximum size of the newly generated chunk file. Only when the maximum and minimum file sizes of the chunks to be generated are, only the chunks within this size will be generated, otherwise the code will remain as it is.

minSize=30000Indicates that the minimum chunk should be 30000 bytes.
maxSize=0Indicates that the maximum size of the chunk is not limited. If set to another reasonable value, for example150000, the generated chunk exceedsmaxSizeIn this case, the chunk will be further split into smaller chunks.

cacheGroups

Cachegroups is a key configuration of splitchunks configuration, which determinesmoduleHow to merge into a new chunk.

{
  vendors: {
    test: /[\\/]node_modules[\\/]/,
    priority: -10
  },
}

staycacheGroupsEach object under configuration can be considered as acacheGroupFor example, in the above code, the key isvendorsObject.

cacheGroup.test

testFor allmoduleFilter, and the filtered modules will be put into this modulecacheGroupIn the corresponding chunk file. In the above example[\\/]node_modules[\\/]aboutmoduleThe path is tested, and finally allnode_ Modules pathThe modules under will be placed invendorsUnder this chunk, this is also generated abovevendors~xxx.jsThe reason for this.

cacheGroup.priority

definitioncacheGroupPriority of. Because for everymoduleFor example, it is possible to match multiple at the same timecacheGroupoftestRule. At this time, you need to decide which one to put according to prioritycacheGroupYes.

name

nameDetermines the name of the generated chunk file. Default totrueIn this case, the generated name format isCachegroup name ~ chunk1 name ~ chunk2 name js, whereChunk1 nameandChunk2 nameBecause of thiscacheGroupContains the code related to these two chunks. If there are more chunks, so on.

automaticNameDelimiter

A careful reader may have noticed the link to the chunk name in the previous section~, actuallyautomaticNameDelimiterThis configuration item is set. Developers can set the connector they want to use through this configuration item.

automaticNameMaxLength

By default, limits are setnameIn sectionChunk1 name ~ chunk2 namePart of the length. If it exceeds the limit, it will be truncated.

For example, if it is set to 3,Vendors chunk1 name ~ chunk2 name jsWill becomevendors~chu~21737d60.js, only the length = 3 is reservedchupart. In case of truncation, an additional character will be added later, which may be a mechanism to avoid duplicate file names.

minChunks

When and onecacheGroupThe number of related chunks exceedsminChunksA new chunk file can be generated only when the.

For example, in the default configuration:

{
  default: {
    minChunks: 2,
    priority: -20,
    reuseExistingChunk: true
  }
}

A careful reader may ask again: what are you talking about nowsplitChunks.minChunksYes, andcacheGroup.minChunksWhat does it matter?

In fact, all configurations under splitchunks will be inherited or overwritten in the cachegroup. So for keyvendorsFor the cachegroup, its minchunks is 1, which is basically unlimited, so node_ The contents in the modules folder will be put into thevendorsThis chunk.

So we know that key isdefaultCachegroup, which will put at least two modules referenced by chunks. If you need to try, you can reference the same module in the bundle file generated by the two entries, and then package it. You should find that the module is placed in the bundle file namedDefault ~ chunk1name ~ chunk2nameIn such a file.

(so far, I hope you have a general understanding of the generation logic of chunk.)


Some other articles on webpack:

  1. Loading of webpack