原理:一个 entry 有一个 html-webpack-plugin 优化:动态获取 entry 和设置 html-webpack-plugin 数量,利用 glob.sync,动态获取 js 文件名
npm i glob -D
webpack.conf.js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const glob = require('glob');
const setMap = () => {
const entry = {};
const htmlWebpackPlugins = [];
const entryFiles = glob.sync(path.join(__dirname, "./src/*/index.js")); // 匹配该路径下的所有 index.js,
console.log("entryFiles", entryFiles);
// 打印的结果
// 返回路径 [ 'D:/workSpace/projects/webpack_study/src/test/index.js' ]
Object.keys(entryFiles).map((index) => {
const entryFile = entryFiles[index];
const match = entryFile.match(/src\/(.*)\/index\.js/);
console.log('match', match);
// 打印的结果
// match [
// 'src/search/index.js',
// 'search',
// index: 36,
// input: 'D:/workSpace/projects/webpack_study/src/search/index.js',
// groups: undefined
// ]
const pageName = match && match[1]; // 获取数组第一个值
entry[pageName] = entryFile;
htmlWebpackPlugins.push(
new HtmlWebpackPlugin({
template: path.join(__dirname, `src/${pageName}/${pageName}.html`), // 需匹配 html 的路径
filename: `${pageName}.html`,
chunks: [pageName],
inject: true
})
);
});
return {
entry,
htmlWebpackPlugins,
};
};
const { entry, htmlWebpackPlugins } = setMap();
entry 放入入口文件,htmlWebpackPlugins 通过 concat 连接 plugins 数组
module.exports = {
entry: entry,
plugins: [].concat(htmlWebpackPlugins)