webpack4系列第五发

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_35534823/article/details/81159772

Code Splitting

code splitting 特性是在 webpack3 中实现的,实现的策略方案也有多种,比如我们在 vue 项目中,通过组件按需引用也可以实现代码切割。主要目的:

  1. 为 Vendor 单独打包(Vendor 指第三方的库或者公共的基础组件,因为 Vendor 的变化比较少,单独打包利于缓存)
  2. 为 Manifest (Webpack 的 Runtime 代码)单独打包
  3. 为不同入口的公共业务代码打包(同理,也是为了缓存和加载速度)
  4. 为异步加载的代码打一个公共的包

webpack3 中,我们通常会有这样的配置:

new webpack.optimize.CommonsChunkPlugin({
  name: 'vendor',
  minChunks (module) {
    return (
      module.resource &&
      /\.js$/.test(module.resource) &&
      module.resource.indexOf(
        path.join(__dirname, '../node_modules')
      ) === 0
    )
  }
}),

new webpack.optimize.CommonsChunkPlugin({
  name: 'manifest',
  minChunks: Infinity
}),

new webpack.optimize.CommonsChunkPlugin({
  name: 'app',
  async: 'vendor-async',
  children: true,
  minChunks: 3
})

这里分别为第三方包,webpack运行时,业务代码分别配置了 CommonsChunkPlugin

那我们 code splitting 的目的在于实现 Long-term caching 。因为我们一般只会修改业务代码,而第三方通常不需要更新,所以分开打包就容易使第三方包的文件进入缓存策略,而业务代码因为文件内容的改变而改变了 hash 值,使得用户请求最新的文件。

webpack4 中移除了 CommonsChunkPlugin 。 具体详情可以看我的另一篇文章 webpack4: 代码分割CommonChunkPlugin的寿终正寝
然后需要使用 SplitChunksPlugin 来进行处理就ok啦~

entry: {
    app: './src/main.js',
    vendor: ['vue', 'axios']
},
optimization: {
  splitChunks: {
    name: 'bundle', // 打包之后的文件名,如果名称与入口点名称匹配,则将删除入口点。
    chunks: 'all' //'all'|'async'|'initial',分别代表了全部 chunk,按需加载的 chunk 以及初始加载的 chunk。 也可以是一个函数
  }
}

这种需要在入口进行指定,我们可以直接把我们在项目中引用的来自 node_modules 的包全部打包成一个文件。

entry: {
    app: './src/main.js'
},
optimization: {
  splitChunks: {
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        name: 'bundle',
        chunks: 'all'
      }
    }
  }
}

猜你喜欢

转载自blog.csdn.net/qq_35534823/article/details/81159772