前端多页面打包通用方案
一、多页面应用(MPA)概念
二、多⻚⾯打包基本思路
module.exports = {
entry: {
index: './src/index.js',
search: './src/search.js ‘ }
};
三、多⻚⾯打包通⽤⽅案
// 安装
npm i glob -D
// 使用
entry: glob.sync(path.join(__dirname, './src/*/index.js'))
四、多⻚⾯打包实操
1.划分好目录
src
目录下建立页面模块名称,页面目录下建立同名称子文件index.html
和index.js
(方便查找)
2.安装并引入glob
和HtmlWebpackPlugin
等
// 安装
npm i glob -D
npm i html-webpack-plugin -D
// 引入
const glob = require('glob');
const HtmlWebpackPlugin = require('html-webpack-plugin');
3.编写设置多页面函数(在webpack.js
文件中)
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] = entryFiles;
htmlWebpackPlugins.push(
new HtmlWebpackPlugin({
template: path.join(__dirname, `src/${pageName}/index.html`),
filename: `${pageName}.html`,
chunks: [pageName],
inject: true,
minify: {
html5: true,
collapseWhitespace: true,
preserveLineBreaks: false,
minifyCSS: true,
minifyJS: true,
removeComments: false
}
}),
)
})
return {
entry,
htmlWebpackPlugins
}
}
4.使用多页面参数及配置入口参数
// 获取参数
const { entry, htmlWebpackPlugins } = setMPA();
// 配置入口参数
module.exports = {
// 多页配置
entry: entry,
output: {
path: path.join(__dirname, 'dist'),
filename: '[name]_[chunkhash:8].js'
},
}
// 使用htmlWebpackPlugins插件
plugins: [
new MiniCssExtractPlugin({
filename: '[name]_[contenthash:8].css'
}),
new CleanWebpackPlugin(),
new HTMLInlineCSSWebpackPlugin(),
].concat(htmlWebpackPlugins) // 把获取到的插件加进来