一、为什么要使用自动化多页面打包
当我们有多个入口时,若是手动一个个去配置,无疑是一个巨大的工作量,也容易出错。webpack提供了 glob 插件,可以让我们通过指定规则的方式,自动打包多页面文件。
二、 实现
通过动态获取entry和设置 html-webpack-plugin数量
// 安装 glob
npm i glob -D
// glob配置
// webpack.prod.js
'use strict';
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptionsCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require("html-webpack-plugin");
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const HTMLInlineCSSWebpackPlugin = require("html-inline-css-webpack-plugin").default;
const glob = require('glob'); // 引入glob
// 增加配置的函数
const setMPA = () => {
const entry = {};
const htmlWebpackPlugins = [];
const entryFiles = glob.sync(path.join(__dirname, './src/*/index.js'));
console.log('entryFiles = ' + entryFiles);
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}.html`,
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: entry, // 定义入口,entry是个数组,包含了所有符合规则的入口文件名
output: {
path: path.join(__dirname, 'dist'),
filename: '[name]_[chunkhash:8].js'
},
mode: 'production',
module: {
....
},
plugins: [
new CleanWebpackPlugin(),
new MiniCssExtractPlugin({
filename: '[name]_[contenthash:8].css'
}),
new OptionsCssAssetsWebpackPlugin({
assetNameRegExp: /\.css$/g,
cssProcessor: require('cssnano')
}),
].concat(htmlWebpackPlugins), // 将构建好的文件数组插入
devServer: {
contentBase: './dist',
hot: true
}
}
三、结果
github项目地址:webpack多页面打包
// 运行打包
npm run build