问题描述
我想捆绑几个 html 文件并将一个 css 文件添加到所有这些文件中.但是我的 webpack 配置只将 css 和 js 捆绑文件添加到 index.html
I want to bundle a couple of html files and add one css files into all of them. But my webpack configuration add only css and js bundled files to index.html
我的文件如下所示:
我想将此 main-hash.js 和 main-hash.css 添加到所有 HTML 文件中:about.html、index.html、contact.html
I want to add this main-hash.js and main-hash.css to all HTML files: about.html, index.html, contact.html
另外,当我从文件加载器中排除 index.html(下面的评论)时,我的 index.html 无法识别公共文件夹 /images
的路径.有什么想法吗??
Also when I exclude index.html (comment below) from file-loader my index.html don't recognize paths for public folder /images
. Any ideas ??
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
}
};
推荐答案
您可以添加多个 HtmlWebpackPlugin 实例,每个 html 文件一个:
You can add multiple instances of the HtmlWebpackPlugin, one for each of your html files:
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 文件中.
This should inject the JS and CSS files into each html file.
这篇关于Webpack 4 - 将 css 文件添加到多个 html 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!