我使用webpack捆绑我的Web应用程序项目。 webpack配置如下所示:
const HtmlWebPackPlugin = require("html-webpack-plugin");
const CopyWebpackPlugin = require("copy-webpack-plugin");
const path = require("path");
const autoprefixer = require('autoprefixer');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
module.exports = {
entry: ["./src/index.js"],
output: {
path: path.resolve(__dirname, "dist"),
filename: "bundle.[hash].js"
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env", "@babel/preset-react"]
}
}
},
{
test: /\.html$/,
use: [
{
loader: "html-loader",
options: {
minimize: true
}
}
]
},
{
test: /\.(sass|scss)$/,
use: [
{
loader: "file-loader",
options: {
name: "style.css"
}
},
{ loader: "extract-loader" },
{ loader: "css-loader",
options: {
minimize: true
}
},
{
loader: "postcss-loader",
options: {
plugins: () => [autoprefixer({ grid: false })]
}
},
{
loader: "sass-loader",
options: {
includePaths: ["./node_modules"]
}
}
]
},
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
use: [
{
loader: "file-loader",
options: {
name: "[name][hash].[ext]",
outputPath: "fonts/"
}
}
]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./public/index.html",
filename: "./index.html"
}),
new CopyWebpackPlugin([
{
from: "public"
}
]),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
};
SCSS模块,我使用文件加载器生成style.css
文件。 index.html的内容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<link rel="stylesheet" href="main.css">
<title>Cockpit</title>
</head>
<body class="mdc-typography">
<button class="mdc-button">
Button
</button>
</body>
</html>
如您所见,样式表文件是硬编码的,但我希望它自动插入index.html
。如何使用html-webpack-plugin
进行操作?
答案 0 :(得分:0)
尝试使用HtmlWebpackIncludeAssetsPlugin
。
plugins: [
new HtmlWebPackPlugin({
template: "./public/index.html",
filename: "./index.html"
}),
new CopyWebpackPlugin([
{
from: "public"
}
]),
new HtmlWebpackIncludeAssetsPlugin({
assets: ['style.css'],
append: true
}),
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
})
]
可能有更多选项,请参阅此处:https://github.com/jharris4/html-webpack-include-assets-plugin