多页面应用打包,这个时候就不太适合,一个一个页面单独的去配置 entry 与 html-webpack-plugin,太繁琐
这个时候我们一般会自动去识别入口文件与模板html,动态配置
假如我们的项目中,我们将多页面统一放入 src/pages 文件夹内,入口文件统一命名 index.js 模板文件统一命名 index.html
// 自动识别文件 我们使用 glob 库
const glob = require('glob');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const setMPA = () => {
const entry = {}
const htmlWebpackPlugins = []
// 匹配 src/pages 内文件夹内有 index.js 的文件
const entryFiles = glob.sync(path.join(__dirname, './src/pages/*/index.js'))
entryFiles.map((entryFile) => {
// 通过正则匹配出文件夹名,也就是页面名
const matchRes = entryFile.match(/src\/pages\/(.*)\/index\.js$/)
const pageName = matchRes && matchRes[1]
entry[pageName] = path.resolve(__dirname, `./src/pages/${pageName}/index.js`)
htmlWebpackPlugins.push(new HtmlWebpackPlugin({
template: path.join(__dirname, `./src/pages/${pageName}/index.html`),
filename: `${pageName}.html`,
chunks: [pageName], // 需要的 chunks
inject: true, // 打包后的 chunks 是否自动注入
minify: {
html5: true,
collapseWhitespace: true,
preserveLineBreaks: false,
minifyCSS: true,
minifyJS: true,
removeComments: false
}
}))
})
return {
entry,
htmlWebpackPlugins
}
}
const {entry, htmlWebpackPlugins} = setMPA()
module.exports = {
entry,
plugins: [].concat(htmlWebpackPlugins)
}