未处理前的webpack.config.js文件【手动增加多页面】

//两个入口
entry: {
index: "./src/index.js",
login: "./src/login.js",
},
//出口
output: {
path: path.resolve(__dirname, "./dist"),
filename: "[name]-[hash:6].js",
},






//插件配置
plugins: [
new htmlWebpackPlugin({
template: "./src/index.html",
filename: "index.html",
chunks: ["main"],
}),
new htmlWebpackPlugin({
template: "./src/index.html",
filename: "login.html",
chunks: ["login"],
}),
new CleanWebpackPlugin(),
new miniCssExtractPlugin({
filename: "css/index-[contenthash:6].css",
}),
],

处理后的webpack.config.js文件【自动在项目目录中查找多页面】

首先改变目录结构

webpack4.0核心概念(八)———— 多页面打包通用方案 MPA_MPA

webpack.config.js主要代码如下

const glob = require("glob");//npm i glob -D

const setMpa = () => {
const entry = {};
const htmlWebpackPlugins = [];
//生成entry
const entryFiles = glob.sync(path.join(__dirname, "./src/*/index.js"));//目录下面有index.js的目录
console.log(entryFiles)
entryFiles.map((item, index) => {
const entryFile = item;
const match = entryFile.match(/src\/(.*)\/index\.js$/);
console.log(match)
const pageName = match[1];
entry[pageName] = entryFile;

htmlWebpackPlugins.push(
new htmlWebpackPlugin({
template: path.join(__dirname, `./src/${pageName}/index.html`),
filename: `${pageName}.html`,
chunks: [pageName, "detail"],
})
);
});

return {
entry,
htmlWebpackPlugins,
};
};

const { entry, htmlWebpackPlugins } = setMpa();

module.exports = {
entry,

plugins: [
...htmlWebpackPlugins,
new CleanWebpackPlugin(),
new miniCssExtractPlugin({
filename: "css/index-[contenthash:6].css",
}),
],
}