10天掌握webpack 4.0 优化篇 (5)抽离公共代码

我们在开发多个页面的项目的时候,有时候会在几个页面中引用某些公共的模块,这些公共模块多次被下载会造成资源浪费,如果把这些公共模块抽离出来只需下载一次之后便缓存起来了,这样就可以避免因重复下载而浪费资源

场景:

项目中 有 a.js  b.js   index.js  other.js 文件

index.js  和 other.js 同样引用了 a.js  b.js  并且都使用了第3方库 jquery 

代码如下:

a.js

console.log('a' + '--------')

b.js

console.log('b' + '--------')

index.js

import './a'
import './b'
console.log('index.js')
import $ from 'jquery'
console.log($)

other.js

import './a'
import './b'
console.log('other.js')
import $ from 'jquery'
console.log($)

配置webpack.config.js文件

  optimization: {
    //分割代码快
    splitChunks: {
      // 缓存组
      cacheGroups: {
        // 公共模块
        common: {
          chunks: 'initial',
          minSize: 0,
          minChunks: 2
        },
        vendor: {
          priority: 1,//添加权重
          test: /node_modules/,//把这个目录下符合下面几个条件的库抽离出来
          chunks: 'initial',//刚开始就要抽离
          minSize: 0,//大小大于0字节的时候需要抽离出来
          minChunks: 2,//重复2次使用的时候需要抽离出来\
        }
      }
    }
  },

 

const path = require('path')
let webpack = require('webpack')
let htmlWebpckPlugin = require('html-webpack-plugin')
module.exports = {
  mode: 'production',
  optimization: {
    //分割代码快
    splitChunks: {
      // 缓存组
      cacheGroups: {
        // 公共模块
        common: {
          chunks: 'initial',
          minSize: 0,
          minChunks: 2
        },
        vendor: {
          priority: 1,//添加权重
          test: /node_modules/,//把这个目录下符合下面几个条件的库抽离出来
          chunks: 'initial',//刚开始就要抽离
          minSize: 0,//大小大于0字节的时候需要抽离出来
          minChunks: 2,//重复2次使用的时候需要抽离出来\
        }
      }
    }
  },
  entry: {
    index: './src/index.js',
    other: './src/other.js',
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist')
  },
  plugins: [
    new htmlWebpckPlugin({
      template: './public/index.html'
    }),
    new webpack.IgnorePlugin(/^\.\/locale/, /moment$/)
  ],
  module: {
    noParse: /jquery|lodash/, // 正则表达式
    rules: [
      {
        test: /\.js?$/,
        include: path.join(__dirname, 'src'),
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            "presets": [
              "@babel/preset-env",
              "@babel/preset-react",
            ]
          }
        }
      }
    ]
  },

}

抽离第3方库需要注意:

这里需要配置权重 priority,因为抽离的时候会执行第一个common配置,入口处看到jquery也被公用了就一起抽离了,不会再执行wendor的配置了,所以加了权重之后会先抽离第三方模块,然后再抽离公共common的,这样就实现了第三方和公用的都被抽离了。

打包:

 

 在打包后的common~index~other.js 我们可以看出:

a.js  与 b.js 被抽离了

 

 

完整代码:

https://gitee.com/guangzhou110/ten-days_to_master_webpack4/tree/master/webpack-dev-3

posted @ 2020-03-15 18:02  1点  阅读(359)  评论(0编辑  收藏  举报