config.js
// entry: 入口js
// template: html打包參照模版
module.exports = {
pages: {
'index': {
src: './src/index.js',
template: 'public/index.html'
},
'myList': {
src: './src/myList.js',
template: 'public/myList.html'
},
'pay': {
src: './src/pay.js',
template: 'public/pay.html'
}
}
}
webpack.config.js
const path = require('path')
const htmlWebpackPlugin = require('html-webpack-plugin') // 引入插件
const config = require('./config/index')
const entry = {}
const htmlArr = []
// 生成入口文件對象
for(let key in config.pages) {
entry[key] = config.pages[key].src
htmlArr.push(
// 想要在生成的不同的html頁面中引入不同的js文件
// 要在插件配置文件中加入:chunks:["入口文件名"],即可,
// 如果不加的話,會在生成的html頁面中引入所有的入口文件
new htmlWebpackPlugin({
template: config.pages[key].template,
filename: `${key}.[chunkhash].html`,
chunks: [`${key}`], // mylist.html中只引入mylist.js ...
inject: 'true'
}) // 初始化
)
}
module.exports = {
entry: entry,
output: {
filename: 'js/[name].[chunkhash].js', // 在filename中也可以指定路徑
path: path.join(__dirname, 'dist')
},
plugins: htmlArr
}
文件打包好的目錄: