# 配置多页应用
本质是使用html-webpack-plugin 多个实例。
# 定义多个入口
辅助函数:getEntry
function getEntry() {
let entry = {};
//读取src目录所有page入口
glob.sync('./src/*.js').forEach(function(name){
let start = name.indexOf('src/') + 4;
let end = name.length - 3;
let eArr = [];
let n = name.slice(start,end);
entry[n] = name;
})
return entry;
}
//配置页面
let entryObj = getEntry();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 动态添加多个html-webpack-plugin 实例
//读取src目录所有page入口
let getHtmlConfig = function(name,chunks){
return {
template:`./src/page/${name}.html`,
filename:`pages/${name}.html`,
inject:true,
hash:false,
chunks:[name]
}
}
let htmlArray = [];
Object.keys(entryObj).forEach(function(element){
htmlArray.push({
_html:element,
title:'',
chunks:[element]
})
})
//自动生成html模板
htmlArray.forEach(function(element){
module.exports.plugins.push(new HtmlWebpackPlugin(getHtmlConfig(element._html,element.chunks)));
})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
webpack.config.js
const path = require('path');
const glob = require('glob');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin"); //将css以link的方式引入,否则就用style-loader
const CopyPlugin = require('copy-webpack-plugin');
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
module.exports={
mode:"development",
entry:entryObj,
devtool:'cheap-module-eval-source-map',
output:{
filename:'js/[name].[hash:8].js',
path:path.resolve(__dirname,'dist')
},
module:{
rules:[
{
test:/\.js$/,
use:{
loader:'babel-loader',
options:{
presets:['@babel/preset-env']
}
}
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader" // 将 CSS 转化成 CommonJS 模块
},
{
loader: "sass-loader" // 将 Sass 编译成 CSS
}]
},
]
},
plugins:[
new CleanWebpackPlugin(),
new CopyPlugin([
{from:"public",to:"public"}
]),
new MiniCssExtractPlugin({
filename: "css/[name].css",
chunkFilename: "css/[id].css"
}),
]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
← plugin原理