- webpack多入口页面配置中,使用html-webpack-plugin如何对应不同html页面加载的js路径?
如果不指定output.filename,默认的filename是"main.js",每个页面都会包含。通过指定 chunk 文件即可对应上.
const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
mode: 'development',
entry: './src/index.js',
output: {
path: path.resolve(__dirname, 'public'),
// filename: 'bundle.js'
},
module: {
rules: [
{ test: /\.css$/, use: ['style-loader','css-loader'] },
{ test: /\.scss$/, loaders: ["style-loader", "css-loader", "sass-loader"]},
{ test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/, use: ['file-loader'] },
{ test: /\.(html)$/, use: {loader: 'html-loader'}}
]
},
plugins: [
new HtmlWebpackPlugin({
title:'Home',
filename: 'index.html',
template: 'src/index_template.html',
}),
new HtmlWebpackPlugin({
title:'Sub Page',
filename: 'subpage.html',
template: 'src/pages/subpage.html',
}),
new HtmlWebpackPlugin({
title:'404 页',
filename: '404.html',
template: 'src/pages/404.html',
}),
]
...
};
指定 chunk 文件:const HtmlWebpackPlugin = require('html-webpack-plugin');
const path = require('path');
module.exports = {
mode: 'development',
// entry: './src/index.js',
entry: {
index:'./src/index.js',
subpage:'./src/pages/subpage.js',
"404":'./src/pages/404.js'
},
output: {
path: path.resolve(__dirname, 'public'),
// filename: 'bundle.js'
filename: 'js/[name]-[chunkhash].js',
},
module: {
rules: [
{ test: /\.css$/, use: ['style-loader','css-loader'] },
{ test: /\.scss$/, loaders: ["style-loader", "css-loader", "sass-loader"]},
{ test: /\.(png|jpg|jpeg|gif|svg|woff|woff2|ttf|eot)$/, use: ['file-loader'] },
{ test: /\.(html)$/, use: {loader: 'html-loader'}}
]
},
plugins: [
new HtmlWebpackPlugin({
title:'Home',
filename: 'index.html',
template: 'src/index_template.html',
chunks: ['index']
}),
new HtmlWebpackPlugin({
title:'Sub Page',
filename: 'subpage.html',
template: 'src/pages/subpage.html',
chunks: ['subpage']
}),
new HtmlWebpackPlugin({
title:'404 页',
filename: '404.html',
template: 'src/pages/404.html',
chunks: ['404']
}),
],
//引入绝对路径
resolve: {
alias: { '@': path.resolve(__dirname, 'src') }
},
devServer: {
contentBase: "./public",//本地服务器所加载的页面所在的目录
historyApiFallback: true,//不跳转
inline: true//实时刷新
}
};
- html-webpack-plugin 使用总结
html-webpack-plugin 的作用是:当使用 webpack打包时,创建一个 html 文件,并把 webpack 打包后的静态文件自动插入到这个 html 文件当中。
// 默认情况
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: 'index.js',
output: {
path: __dirname + '/dist',
filename: 'index_bundle.js'
},
plugins: [
new HtmlWebpackPlugin()
]
}
html-webpack-plugin 默认将会在 output.path 的目录下创建一个 index.html 文件, 并在这个文件中插入一个 script 标签,标签的 src 为 output.filename。
- entry的key会作为output中的name