使用webpack搭建单页面程序十分常见,但在实际开发中我们可能还会有开发多页面程序的需求,因此我研究了一下如何使用webpack搭建多页面程序。
原理
将每个页面所在的文件夹都看作是一个单独的单页面程序目录,配置多个entry
以及html-webpack-plugin
即可实现多页面打包。
下面为本项目目录结构
.
├─ src
│ └─ pages
│ ├─ about
│ │ ├─ index.css
│ │ ├─ index.html
│ │ └─ index.js
│ └─ index
│ ├─ index.css
│ ├─ index.html
│ └─ index.js
└─ webpack.config.js
单页面打包基础配置
首先我们来看一下单页面程序的 webpack 基础配置
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/index.js',
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
}),
],
output: {
path: path.resolve(__dirname, './dist'),
filename: 'bundle.js',
},
};
要想将其改为多页面程序,就要将它的单入口和单 HTML 模板改为多入口和多 HTML 模板
多页面打包基础配置
改造入口
传统的多入口写法可以写成键值对的形式
module.exports = {
entry: {
index: './src/pages/index/index.js',
about: './src/pages/about/index.js',
},
...
}
这样写的话,每增加一个页面就需要手动添加一个入口,比较麻烦,因此我们可以定义一个根据目录生成入口的函数来简化我们的操作
const glob = require('glob');
function getEntry() {
const entry = {
};
glob.sync('./src/pages/**/index.js').forEach((file) => {