我的
webpack.config.js
里有:
const data = require('./src/data.json');
...
new HtmlWebpackPlugin({
template: "src/index.hbs",
filename: "index.html",
templateParameters: {
data: data
},
}),
...
module: {
rules: [
{
test: /\.hbs$/,
loader: "handlebars-loader"
}
],
},
devServer: {
static: './dist',
hot: true,
liveReload: true,
open: false,
watchFiles: ['src/**/*.hbs', './src/data.json'],
},
当使用
npm start
运行时,热重载适用于我的 JS 模块,但如果我对 data.json
进行更改则不行。当我更改 JSON 文件时,如何重新加载开发服务器?
您可以尝试使用现代强大的html-bundler-webpack-plugin代替
html-webpack-plugin
。
使用 data 插件选项作为 JSON 或 JS
filename
在数据文件中的变量更改后重新编译并重新加载页面,而无需重新启动 Webpack。
例如,有您的页面模板
./src/index.hbs
:
<!DOCTYPE html>
<html>
<head>
<!-- `title` is the vaiable passed from data.json via webpack -->
<title>{{ title }}</title>
<!-- relative path to favicon source file -->
<link href="./favicon.ico" rel="icon" />
<!-- relative path to SCSS source file -->
<link href="./style.scss" rel="stylesheet" />
<!-- relative path to JS source file -->
<script src="./main.js" defer="defer"></script>
</head>
<body>
<h1>Hello World!</h1>
<!-- relative path to image source file -->
<img src="./images/picture.png" />
</body>
</html>
Webpack 配置示例:
const path = require('path');
const HtmlBundlerPlugin = require('html-bundler-webpack-plugin');
module.exports = {
plugins: [
new HtmlBundlerPlugin({
entry: [
{
import: 'src/index.hbs',
filename: 'index.html',
data: 'src/data.json', // <= relative path to data used in this page
},
// add your pages here
],
data: 'src/data.json', // <= relative path to global data passed into all pages
preprocessor: 'handlebars', // <= enable support *.hbs templates
preprocessorOptions: {
partials: [
'src/partials/', // path to your partials
],
},
}),
],
module: {
rules: [
{
test: /\.(css|sass|scss)$/,
use: ['css-loader', 'sass-loader'],
},
{
test: /\.(ico|png|jp?g|webp|svg)$/,
type: 'asset/resource',
generator: {
filename: 'img/[name].[hash:8][ext][query]',
},
},
],
},
// enable live reload
devServer: {
static: path.join(__dirname, 'dist'),
watchFiles: {
paths: ['src/**/*.*'],
options: {
usePolling: true,
},
},
},
};
这是 handlebars 示例 使用 JSON 数据文件作为传递到模板的外部数据。
附注您可以在 GitHub 上创建一个小型存储库,然后我可以帮助您完成您的项目。