1、多入口文件

  1. entry:{
  2. index:path.join(srcPath,'index.js')
  3. other:path.join(srcPath,'other.js')
  4. }
output:{
    filename:'[name].[contenHash:8].js' // name为entry的文件名
}

Html webpack plugin : 会在打包之后自动创建一个index.html 并将打包好的js自动引入这个html
npm install —save-dev html-webpack-plugin

const HtmlWebpackPlugin = require('html-webpack-plugin');
plugins: [new HtmlWebpackPlugin()]

    plugins: [new HtmlWebpackPlugin({
        // 指定打包的模板, 如果不指定会自动生成一个空的
        template: "./index.html",
        minify: {
            // 告诉htmlplugin打包之后的html文件需要压缩
            collapseWhitespace: true,
        },
      chunks:['index']
    })]

* 要配置chunks:[‘index’],告诉html引入那个js
额外plugin:clean

3.clean-webpack-plugin使用
https://github.com/johnagan/clean-webpack-plugin
3.1安装clean-webpack-plugin
npm install --save-dev clean-webpack-plugin
3.2配置clean-webpack-plugin
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
plugins: [new CleanWebpackPlugin()]

2、如何抽离、压缩css
使用mini-css-extract-plugin
在prod环境下,使用MiniCssExtractPlugin.loader替换style.loader

      {
        test: /\.css$/,
        use: [
          MiniCssExtractPlugin.loader,
          {
            loader: 'css-loader',
          },
          {
            loader: 'postcss-loader',
            options: postcssConfig,
          },
        ],
      },

在plugin中,使用MinCssExtract将css从js抽离

    new MiniCssExtractPlugin({
                filename:'css/main.[contentHash:8].css'
    }),

压缩:在optimization中添加minimizer

optimization:{
    minimizer:{
            new CssMinimizerPlugin({
        parallel: true,
      }),
  }
}

抽离公共代码和第三方库

1、多个文件引用一个公共文件,打包会打包多次
2、比如引用第三方库,lodash,修改改文件后,lodash还会跟着打包
在optimization中 分割代码块

splitChunks:{
    chunks:all,

    //缓存分组 
    cacheGroups:{
      // 第三方模块
        vendor:{
          name:'vendor',
        priority:1,
        test:/node_modules/,
         minSize:0,
         minChunks:1
      }
      // 公共组件
        common:{
          name:'common',
        priority:0,
         minSize:0,
         minChunks:2
      }
    }
}

htmlWebpackPlugin需要考虑代码分割 chunks:[‘vendor’,’common’]

懒加载 :import语法 自定义chunk

import(‘’./xxx.js).then(res=>{})

DllPlugin

entry:{
    react:['react','react-dom']
},
output:{
    filename:'[name].dll.js',
  path: disPath,
  library:'_dll_[name]'
},
plugins:[
    new DllPlugin({
      name:'_dll_[name]',
    path:path.join(distPath,'[name].manifest.json')
  })
]