單頁應用SPA:只有一個html
文檔,經過js
感知url
的變化,js
動態的將當前頁面內容清除掉,而後將下一個頁面的內容掛載到頁面上,這就是單頁應用,每次跳轉了解不須要請求新的html
文檔;html
多頁應用MPA:每一次頁面跳轉,服務器都會返回一個新的html
文檔,這種類型的網站就是多頁網站,也叫多頁應用。html5
每個頁面對應一個entry
和一個html-webpack-plugin
,代碼示例以下:webpack
module.exports = {
entry:{
index:'./src/index/index.js',
search:'./src/search/index.js'
}
}
複製代碼
缺點:每次新增或刪除頁面都須要修改webpack
配置,頁面過多時,會寫很是多的html-webpack-plugin
配置,形成webpack
配置文件冗長,不利於維護。web
每次打包時動態獲取entry
,根據entry
信息自動設置html-webpack-plugin
數量。bash
頁面內容所有放在src
文件夾下面,而且每個頁面單獨一個文件夾,html
和js
文件所有命名爲index
,使用glob
模塊的glob.sync
動態獲取src
文件夾下面的各個子文件夾中的index.js
文件做爲每一個頁面的入口文件。服務器
獲取全部的入口文件路徑:post
const entryFiles = glob.sync(path.join(__dirname,'./src/*/index.js'))
複製代碼
遍歷入口文件集合建立html-webpack-plugin
設置:網站
const entry = {};//入口對象
const htmlWebpackPlugins = [];//html-webpack-plugin設置集合
Object.keys(entryFiles).map(index => {
const entryFil = entryFiles[index];
//獲取文件夾名稱
const match = entryFil.match(/src\/(.*)\/index\.js/);
const pathname = match && match[1];
//設置入口對象
entry[pathname] = entryFil;
//設置html-webpack-plugin設置
htmlWebpackPlugins.push(
new HtmlWebpackPlugin({
template:path.join(__dirname,`src/${pathname}/index.html`),
filename:`${pathname}.html`,
chunks:[pathname],
inject:true,
minify:{
html5:true,
collapseWhitespace:true,
preserveLineBreaks:false,
minifyJS:true,
minifyCSS:true,
removeComments:false
}
})
)
})
複製代碼
修改webpack
配置:ui
module.exports = {
entry:entry,
...
plugins:[
...
].concat(htmlWebpackPlugins)
}
複製代碼
const path = require('path');
const glob = require('glob');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const setMpa = () => {
const entry = {};//入口對象
const htmlWebpackPlugins = [];//html-webpack-plugin配置
//獲取入口文件
const entryFiles = glob.sync(path.join(__dirname,'./src/*/index.js'));
Object.keys(entryFiles).map(index => {
const entryFil = entryFiles[index];
//獲取文件夾名稱
const match = entryFil.match(/src\/(.*)\/index\.js/);
const pathname = match && match[1];
//配置入口文件對象
entry[pathname] = entryFil;
//配置html-webpack-plugin
htmlWebpackPlugins.push(
new HtmlWebpackPlugin({
template:path.join(__dirname,`src/${pathname}/index.html`),
filename:`${pathname}.html`,
chunks:[pathname],
inject:true,
minify:{
html5:true,
collapseWhitespace:true,
preserveLineBreaks:false,
minifyJS:true,
minifyCSS:true,
removeComments:false
}
})
)
});
return {
entry,
htmlWebpackPlugins
}
};
const { entry, htmlWebpackPlugins } = setMpa();
module.exports = {
entry:entry,
output:{
path:path.join(__dirname,'dist'),
filename:'[name]_[chunkhash:5].js'
},
mode:'production',
module:{
rules:[
...
]
},
plugins:[
new CleanWebpackPlugin(),
].concat(htmlWebpackPlugins)
}
複製代碼
系列連接:url