多页面打包

使用glob插件并通过

1
yarn add glob html-webpack-plugin -D

配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* @description:
* @author: 小康
* @url: https://xiaokang.me
* @Date: 2021-01-02 17:18:46
* @LastEditTime: 2021-01-02 17:18:46
* @LastEditors: 小康
*/
const glob = require('glob')
const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const setMPA = () => {
const entry = {}
const htmlWebpackPlugins = []
const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js'))

Object.keys(entryFiles).map((index) => {
const entryFile = entryFiles[index]

const match = entryFile.match(/src\/(.*)\/index\.js/)
const pageName = match && match[1]

entry[pageName] = entryFile
htmlWebpackPlugins.push(
new HtmlWebpackPlugin({
inlineSource: '.css$',
template: path.join(__dirname, `src/${pageName}/index.html`),
filename:
pageName === 'index' ? 'index.html' : `${pageName}/index.html`,
// 为不同页面使用配合的chunks
chunks: ['vendors', pageName],
inject: true,
minify: {
html5: true,
collapseWhitespace: true,
preserveLineBreaks: false,
minifyCSS: true,
minifyJS: true,
removeComments: false
}
})
)
})
return {
entry,
htmlWebpackPlugins
}
}
const { entry, htmlWebpackPlugins } = setMPA()
module.exports = {
entry,
output: {
path: path.join(__dirname, 'dist'),
filename: 'js/[name]_[chunkhash:8].js'
},
plugins: [].concat(htmlWebpackPlugins),
mode: 'production'
}

开发时需要配置的文件结构

1
2
3
4
5
6
7
8
src               
├─ about
│ ├─ index.html
│ └─ index.js
└─ index
├─ index.html
└─ index.js

生成的目录结构

1
2
3
4
5
6
7
8
dist                     
├─ about
│ └─ index.html
├─ js
│ ├─ about_c68ef4bd.js
│ └─ index_7401bbd4.js
└─ index.html

我的webpack配置