多页面应用(MPA)概念
每⼀次⻚⾯跳转的时候,后台服务器都会给返回⼀个新的 html ⽂档,这种类型的⽹站就是多⻚⽹站,也叫做多⻚应⽤。
多页面打包思路
- 每个页面对应一个entry,一个html-webpack-plugin
- 需要解决避免每次新增或删除页面都要修改webpack配置
- 使用glob模块,用它可以查找符合特定规则的文件路径名
webpack中写入这段核心代码能够实现自动化添加或删除页面的功能,但是需要文件目录需要保持一定规律。如:
{
index: ‘d:/code/webpack/my-project/chapter2/src/index/index.js’,
search: ‘d:/code/webpack/my-project/chapter2/src/search/index.js’
}
入口都是在src/*/index.js
const setMPA = () => {
const entry = {}
const htmlWebpackPlugins = []
const entryPaths = glob.sync(path.join(__dirname, './src/*/index.js'))
Object.keys(entryPaths).forEach(index => {
const entryPath = entryPaths[index]
const match = entryPath.match(/src\/(.*)\/index\.js/)
const pageName = match && match[1]
entry[pageName] = entryPath
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 }
}
const { entry, htmlWebpackPlugins } = setMPA();