webpack补充点---查漏补缺

 css的处理:

1 css在dev环境下,可以打包在 html的 style中

{
     test: /\.css$/,
     // loader 的执行顺序是:从后往前
     loader: ['style-loader', 'css-loader', 'postcss-loader'] 
     // 加了 postcss
}

2. css在build线上环境下,要单独抽离出来,

module:{
  rules:[
    {
      // 抽离 css
      {
          test: /\.css$/,
          loader: [
              MiniCssExtractPlugin.loader,  // 注意,这里不再用 style-loader
              'css-loader',
              'postcss-loader'
          ]
      }
    }
  ]
},
plugins: [
  // 抽离 css 文件
  new MiniCssExtractPlugin({
      filename: 'css/main.[contentHash:8].css'
  })
],
optimization: {
  // 压缩 css
  minimizer: [new TerserJSPlugin({}), new OptimizeCSSAssetsPlugin({})],
}

提取公共代码chunk块的技术:splitChunks 分割代码块 和使用dll 打包公共代码块 虽然都可以提取公共代码,但是 splitChunks 会在每次webpack 打包的时候 都要执行 而使用 dll打包之后 只需要打包一次。

splitChunks: {
  chunks: 'all',
  // 缓存分组
  cacheGroups: {
      // 第三方模块
      vendor: {
          name: 'vendor', // chunk 名称
          priority: 1, // 权限更高,优先抽离,重要!!!
          test: /node_modules/,
          minSize: 0,  // 大小限制
          minChunks: 1  // 最少复用过几次
      },
      // 公共的模块
      common: {
          name: 'common', // chunk 名称
          priority: 0, // 优先级
          minSize: 0,  // 公共模块的大小限制
          minChunks: 2  // 公共模块最少复用过几次
      }
  }
}

对应的html中也要引入该trunk

// 多入口 - 生成 index.html
new HtmlWebpackPlugin({
  template: path.join(srcPath, 'index.html'),
  filename: 'index.html',
  // chunks 表示该页面要引用哪些 chunk (即上面的 index 和 other),默认全部引用
  chunks: ['index', 'vendor', 'common']  // 要考虑代码分割
}),
splitChunks

猜你喜欢

转载自www.cnblogs.com/xiaozhumaopao/p/12730586.html