定义

同时配置多个入口文件并且打包出对应的出口文件。并且出口文件引用对应的chunk。

文件目录

  1. |--dist
  2. |--src
  3. | |--index.js
  4. | |--other.js
  5. | |--sum.js
  6. |--webpack.config.js

生成效果

|--dist
  |--index.html
  |--other.html
  |--index.[hash].js
  |--other.[hash].js
|--src 
  |--index.js
  |--other.js
  |--sum.js
|--webpack.config.js

需要生成如上代码中 dist 中的文件。并且index.html 只引用 index.[hash].js,other.html 只引用other.js。

具体配置

let HtmlWebpackPlugin = require('html-webpack-plugin');
let { CleanWebpackPlugin } = require('clean-webpack-plugin');
let path = require('path');

let htmlPlugins = ['index', 'other'].map(chunkName => {
  return new HtmlWebpackPlugin({
    filename: `${chunkName}.html`,
    inject: 'body',
    /** chunks 属性代表了当前html需要引用的chunk **/
    chunks: [chunkName]
  })
})

module.exports = {
  mode: 'development',
  entry: {    // 配置多入口
    index: './src/index.js',
    other: './src/other.js'
  },
  // name 为变量,是entry中的入口名。
  // contenthash 是根据文件内容生成的哈希值,防止缓存导致js不加载
  output: {
    filename: '[name].[contenthash].js',
    path: path.resolve(__dirname, 'dist')
  },
  plugins: [
    new CleanWebpackPlugin(),
    ...htmlPlugins
  ]

}

多入口打包最重要的就是 HtmlWebpackPlugin 的循环调用,生成不同模块的 html 文件。
我这边采用的map,返回 HtmlWebpackPlugin 数组。这样比较方便,其中最重要的是 chunks 属性,决定了当前生成html需要引用的chunk。

运行

yarn build => npx webpack

结果
image.png
image.png
image.png

哈希值

contenthash 可以指定长度,只要在 后面加个数字即可如下:

module.exports = {
  //....
  output:{
    filename: "[name].[contenthash:8].js",
    path: path.resolve(__dirname, 'dist')
  }
  //...
}