初始化
cd 項目名
webpack init
創建第二頁面與其頭文件
touch page2.html
touch src/page2.js
修改page2.js
console.log("success")
修改webpack.config.js
添加page2.html至plugins項,添加src/page2.js至entry項
最終模板:
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const WorkboxWebpackPlugin = require('workbox-webpack-plugin');
const isProduction = process.env.NODE_ENV == 'production';
const config = {
entry: {
main: './src/index.js',
page2: './src/page2.jz'
},
output: {
path: path.resolve(__dirname, 'dist'),
},
devServer: {
open: true,
host: 'localhost',
},
plugins: [
new HtmlWebpackPlugin({
template: 'index.html',
filename: 'index.html',
chunks: ['main']
}),
HtmlWebpackPlugin({
template: 'page2.html',
filename: 'page2.html',
chunks: ['page2']
})
],
module: {
rules: [
{
test: /\.(eot|svg|ttf|woff|woff2|png|jpg|gif)$/i,
type: 'asset',
},
],
},
};
module.exports = () => {
if (isProduction) {
config.mode = 'production';
config.plugins.push(new WorkboxWebpackPlugin.GenerateSW());
} else {
config.mode = 'development';
}
return config;
};
運行webpack serve,進入網址: localhost:3000/page2.html
(根據實際配置自行更改)
打開控制枱有"success"輸出