Skip to content

webpack 分包加载用的是哪个,分包的原理?

加快首页的请求速度,只有其他模块,只有当需要的时候才会加载对应 js webpack 4 最大的改动就是废除了 CommonsChunkPlugin 引入了 optimization.splitChunks。 如果你的 mode 是 production,那么 webpack4 就会自动开启 Code Splitting。 虽然在 webpack4 会自动开启 Code Splitting,但是随着项目工程的最大, 这往往不能满足我们的需求,我们需要再进行个性化的优化。

jsonp

js
// vue.config.js

modules.export = {
  // ... 
	configureWebpack: config => {
    // ...
  		
    // chuns 有几个参数
    // all: 不管文件是动态还是非动态载入,统一将文件分离。当页面首次载入会引入所有的包
    // async: 将异步加载的文件分离,首次一般不引入,到需要异步引入的组件才会引入。
    // initial:将异步和非异步的文件分离,如果一个文件被异步引入也被非异步引入,那它会被打包两次(注意和all区别),用于分离页面首次需要加载的包。
     config.optimization = {
      splitChunks: {
        cacheGroups: {
          qurender: {
            name: 'qu-render', // 单独将 qu-render 拆包
            chunks: 'async', // 异步加载
            test: /[\\/]node_modules[\\/](qu-render)[\\/]/,
            priority: 10, // 权重
            enforce: true
          },
          'template-components': {
            name: 'template-components',
            chunks: 'async',
            test: /[\\/]node_modules[\\/](template-components)[\\/]/,
            priority: 10,
            enforce: true
          },
          // 名字自己起
          'async-common-group': {
            chunks: 'async',
            test: /[\\/]node_modules[\\/](realia|primary_template|lottie-web|video\.js)[\\/]/,
            priority: 10, 
            name: 'async-common-group'
          },
          // 项目大,公共文件不可控,故未配置 commons 
          // commons: {
          //   name: 'commons',
          //   chunks: 'all', // 页面首次加载,需要引入
          //   minChunks: 2, // 重复引入了2次
          //   enforce: true
          // }
        }
      }
    };
    
    
  }
  // ... 
}

在 MIT 许可下发布