gpt4 book ai didi

javascript - 我如何在构建期间获取 webpack block 哈希?

转载 作者:行者123 更新时间:2023-11-29 21:05:24 26 4
gpt4 key购买 nike

如何用字符串替换我的 HTML 模板中指向当前 block 哈希的变量?

我的 HTML 模板如下所示:

<html>
<head>
<link href="$css" rel="stylesheet">
</head>
<body>
<h1>Hello World</h1>
</body>
</html>

我试图让它像这样构建:

<html>
<head>
<link href="app.c824da43.css" rel="stylesheet">
</head>
<body>
<h1>Hello World</h1>
</body>
</html>

我尝试使用 [name].[chunkhash:8].css 替换字符串,但它呈现为字面意思:

<html>
<head>
<link href="[name].[chunkhash:8].css" rel="stylesheet">
</head>
<body>
<h1>Hello World</h1>
</body>
</html>

我的项目:

.
├── dist
│   ├── app.c824da43.css
│   └── index.html
├── html
│   └── index.html
├── package.json
├── sass
│   └── main.scss
└── webpack.config.js

我的webpack.config.js

var webpack = require('webpack');
var outdir = __dirname + '/dist';
const ExtractTextPlugin = require("extract-text-webpack-plugin");

module.exports = {
entry: {
app: [
'./sass/main.scss',
'./html/index.html',
]
},
output: {
path: outdir,
filename: '[name].[chunkhash:8].js'
},
module: {
rules: [
{
test: /\.s[ac]ss$/,
use: ExtractTextPlugin.extract({
use: ['css-loader', 'sass-loader']
})
},
{
test: /\.html$/,
use: [
{
loader: "file-loader",
options: {
name: "/[name].[ext]",
},
},
{
loader: 'string-replace-loader',
query: {
search: /\$css/,
// What do I need to put here?
replace: '/[name].[chunkhash:8].css'
}
},
{
loader: "extract-loader",
},
{
loader: 'html-loader',
options: {
minimize: true,
removeComments: true,
collapseWhitespace: true
}
}
]
}
]
},
plugins: [
new ExtractTextPlugin("[name].[chunkhash:8].css"),
]
};

我的package.json

{
"devDependencies": {
"css-loader": "^0.28.4",
"extract-loader": "^0.1.0",
"extract-text-webpack-plugin": "^2.1.0",
"file-loader": "^0.11.1",
"html-loader": "^0.4.5",
"node-sass": "^4.5.3",
"sass-loader": "^6.0.5",
"string-replace-loader": "^1.2.0",
"webpack": "^2.6.1"
}
}

Demo with solution

最佳答案

删除 index.html webpack 配置的入口点。使用 HtmlWebpackPlugin 复制您的 index.html。该插件将自动添加 CSS <link>标记到您生成的 html。

参见 https://github.com/jantimon/html-webpack-plugin

如果使用了插件,所有的缩小都应该在插件内部完成,而不是在 /\.html$/ 中的 html-loader 中完成。规则。

new HtmlWebpackPlugin({
template: 'html/index.html',
filename: 'index.html',
minify: {
collapseWhitespace: true,
removeComments: true
}
})

关于javascript - 我如何在构建期间获取 webpack block 哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44355577/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com