单页应用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