美文网首页
webpack4 maxAsyncRequests记录

webpack4 maxAsyncRequests记录

作者: 拉面的无聊时光 | 来源:发表于2019-02-28 19:03 被阅读0次

optimization 生产环境默认配置 webpack版本 4.29.5

 splitChunks: {
    hidePathInfo: true,
    chunks: 'all',
    minSize: 30000,
    minChunks: 1,
    maxAsyncRequests: 5,
    automaticNameDelimiter: '~',
    maxInitialRequests: 3,
    name: true,
    cacheGroups: {
        default: {
            reuseExistingChunk: true,
            minChunks: 2,
            priority: 20
        },
        vendors: {
            automaticNamePrefix: 'vendors',
            test: /[\\\/]node_modules[\\\/]/,
            priority: -10
        }
    }
}

cacheGroups 缓存组

Cache groups can inherit and/or override any options from splitChunks.*; but test, priority and reuseExistingChunk can only be configured on cache group level. To disable any of the default cache groups, set them to false.

缓存组可以继承重写SplitChunks中的任何属性;但是testpriorityReuseExistingChunk只能在缓存组级别配置 . 也就是说真正起作用的是cacheGroups, SplitChunks中设置属性仅仅是基本配置而已.

这里只关注maxInitialRequestsmaxInitialRequests

测试demo

chunks设置为all 处理所有chunks

//webpack.config.js
splitChunks: {
    hidePathInfo: true,
    chunks: 'all',
    minSize: 30000,
    minChunks: 1,
    maxAsyncRequests: 5,
    automaticNameDelimiter: '~',
    maxInitialRequests: 3,
    name: true,
    cacheGroups: {
        default: {
            reuseExistingChunk: true,
            minChunks: 2,
            priority: 20
        },
        vendors: {
            automaticNamePrefix: 'vendors',
            test: /[\\\/]node_modules[\\\/]/,
            priority: -10
        }
    }
}
//entry.js

setTimeout(() => {import('./big.js') }, 4000) 
setTimeout(() => {import('./help1.js') }, 3000)
setTimeout(() => {import('./help2.js') }, 2000)
setTimeout(() => {import('./help3.js') }, 1000)


//big.js>30kb
import s1 from 'help1.js'

//'help1.js >30kb
import s2 from 'help2.js'

//'help2.js >30kb
import s3 from 'help3.js'

//'help3.js  >30kb

maxAnyscRequests 按需加载并发最大请求数

  • 默认配置编译 maxAsyncRequests=5:


    4.png

当按需加载import('./big.js')时,会并发请求 big.js ,help1.js, help2.js,help3.js 4个文件
当按需加载import('./help1.js')时,会并发请求 help1.js, help2.js,help3.js 3个文件
当按需加载import('./help2.js')时,会并发请求 help2.js,help3.js 2个文件
当按需加载import('./help3.js')时,会并发请求 help3.js 1个文件

  • 当我们调整maxAsyncRequests的值为1时:


    3.png

当按需加载import('./big.js')时,会并发请求 1个文件 (big.js ,help1.js, help2.js,help3.js 合并而成)
当按需加载import('./help1.js')时,会并发请求 1个文件(help1.js, help2.js,help3.js 合并而成)
当按需加载import('./help2.js')时,会并发请求 1个文件 (help2.js,help3.js 合并而成)
当按需加载import('./help3.js')时,会并发请求 1个文件 help3.js 1个文件

很明显,当maxAsyncRequests=1 限制时,公共代码没有分离,虽然只请求一次, 但是导致重复加载了公共chunk,代码严重冗余.当maxAsyncRequests = 5 时, 代码没有冗余,但是请求big.js时,并发发起了4次请求. 在此entry.js业务中,明显要maxAsyncRequests=5要明显优于maxAsyncRequests=1

对于任何业务来说,没有最好的配置,只有最合适的配置.

相关文章

网友评论

      本文标题:webpack4 maxAsyncRequests记录

      本文链接:https://www.haomeiwen.com/subject/mzafuqtx.html