多頁面應用(MPA)
概念:
每一次頁面跳轉的時候,後臺服務器都會返回一個新的html文檔,這種類型的網站也就是多頁網站,也叫做多頁應用
優勢:
- 頁面之間的解耦
-
更利於SEO
多頁面打包基本思路:
每個頁面對應一個entry,一個html-webpack-plugin
缺點:每次新增或刪除頁面都需要修改webpack配置
多頁面應用通用打包方案
動態獲取entry和設置html-webpack-plugin
利用glob.sync entry:glob.sync(path.join(__dirname,'./src*/index.js'))
上面我們簡單的理了一下思路,那麼下面我們就開始操作:
1.安裝依賴
cnpm i glob html-webpack-plugin -D
2.src下新建文件,目錄如下圖:
meta.html是我用來資源內聯的,可以忽略
3.package.json中配置命令(個人習慣)
4.webpack.config.js中配置:
"use strict";
const path=require('path');
const HtmlWebpackPlugin=require('html-webpack-plugin');
const glob=require('glob');
const setMPA = () => {
const entry = {};
const htmlWebpackPlugins = [];
// glob.sync同步獲取匹配目錄下的文件
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]=entryFile;
htmlWebpackPlugins.push(
new HtmlWebpackPlugin({
template: path.join(__dirname, `src/${pageName}/index.html`),
filename: `${pageName}.html`,
chunks: ['vendors', pageName],
})
)
})
return {
entry,
htmlWebpackPlugins
}
}
const { entry, htmlWebpackPlugins } = setMPA();
module.exports={
entry:entry,
output: {
path: path.join(__dirname, 'dist'),
filename: '[name]_[chunkhash:8].js'
},
mode:"production",
module:{
},
plugins:[
].concat(htmlWebpackPlugins)
}
5.npm run start打包。
最後我們看一下效果: