我想捆绑几个html文件并将一个css文件添加到所有文件中。但是我的webpack配置仅将css和js捆绑文件添加到index.html
我想将此main-hash.js和main-hash.css添加到所有HTML文件:about.html,index.html,contact.html
也,当我从文件加载器中排除index.html(以下注释)时,我的index.html无法识别公用文件夹/images
的路径。有什么想法吗?
const path = require('path');
const webpack = require('webpack');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
module.exports = {
mode: 'development',
entry: './src/main.js',
output: {
filename: '[name]-[hash:8].js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.ProgressPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html'
}),
new MiniCssExtractPlugin({
filename: '[name].[hash:8].css'
}),
new CleanWebpackPlugin()
],
module: {
rules: [
{
test: /.(js|jsx)$/,
include: [path.resolve(__dirname, 'src')],
loader: 'babel-loader',
options: {
plugins: ['syntax-dynamic-import'],
presets: [
[
'@babel/preset-env',
{
modules: false
}
]
]
},
exclude: '/node_modules/'
},
{
test: /\.(png|jpeg|gif)$/,
use: [
{
loader: 'file-loader',
options: {
publicPath: './src/images',
outputPath: './assets',
name: '[name].[ext]'
}
}
]
},
{
test: /\.(html)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[name].html'
}
},
{ loader: 'extract-loader' },
{
loader: 'html-loader',
options: {
attrs: ['img:src']
}
}
],
// HERE
exclude: path.resolve(__dirname, './src/index.html')
},
{
test: /\.sass$/,
use: [
{
loader: MiniCssExtractPlugin.loader
},
'css-loader',
'sass-loader'
]
}
]
},
optimization: {
splitChunks: {
cacheGroups: {
vendors: {
priority: -10,
test: /[\\/]node_modules[\\/]/
}
},
chunks: 'async',
minChunks: 1,
minSize: 30000,
name: true
}
},
devServer: {
open: true
}
};
答案 0 :(得分:1)
您可以添加多个 HtmlWebpackPlugin 实例,每个html文件一个:
plugins: [
new webpack.ProgressPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html'
}),
new HtmlWebpackPlugin({
filename: 'about.html',
template: './src/about.html'
}),
new HtmlWebpackPlugin({
filename: 'contact.html',
template: './src/contact.html'
}),
new MiniCssExtractPlugin({
filename: '[name].[hash:8].css'
}),
new CleanWebpackPlugin()
],
这应将JS和CSS文件注入每个html文件中。