简介
平时使用webpack多是配置单页应用,但有时会开发多页应用,需要同时打多个页面的包,webpack打多页应用其实也比较简单。
单页应用打包
最简单的单页打包配置大体如下:
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry:{
index:'./src/index.js'
},
output:{
path: path.join(__dirname, 'dist'),
filename: 'js/index.js'
}
...
plugins:[
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html'
})
]
}
如何打包多页面
打包多个页面的关键点其实也比较简单,就是配置多个entry,多次使用HtmlWebpackPlugin打包多个页面,最后把entry和HTML关联起来,让HTML能引用到对的bundle。
对单页配置简单改造后就能支持打包多页面:
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry:{
index: './src/index.js',
detail: './src/detail.js'
},
output:{
path: path.join(__dirname, 'dist'),
filename: 'js/index.js'
}
...
plugins:[
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html'
}),
new HtmlWebpackPlugin({
filename: 'detail.html',
template: './src/detail.html'
})
]
}
上面的配置,针对页面比较少的时候没问题,当页面比较多的时候,一个一个的写显然不合适。
如果页面比较多,可以在编写node代码,读取目前文件夹获取要打包的HTML和entry,然后再向webpack.config.js中插入到 entry 和 plugin。
可以使用glob来完成对文件的查找。