webpack - 将 .json 文件从 html-webpack-plugin 传递到车把模板
问题描述
是否可以通过 html-webpack-plugin 加载 .json 文件并将其传递给我的车把文件?
我目前的设置
const path = require('path');
const fs = require('fs');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const webpack = require('webpack');
const extractCss = new ExtractTextPlugin({
filename: './css/app.css'
});
const pages = fs
.readdirSync(path.resolve(__dirname, 'src/hbs/pages'))
.filter(fileName => fileName.endsWith('.hbs'));
module.exports = {
context: path.resolve(__dirname, "src"),
entry: './js/main.js',
output: {
path: path.resolve(__dirname, './build'),
filename: 'js/app.js',
},
...
...
plugins: [
new CleanWebpackPlugin(['build']),
extractCss,
...pages.map(page => new HtmlWebpackPlugin({
template: 'hbs/pages/'+page,
filename: page
}))
],
module: {
rules: [
//babel-loader
{
test: /\.js$/,
include: /src/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
presets: ['env']
}
}
},
...
...
//handlebars-loader
{
test: /\.(hbs)$/,
loader: "handlebars-loader",
query: {
helperDirs: [
__dirname + "/hbs/helpers"
]
}
}
]
}
};
我想要一个包含 list1.json、list2.json 之类的文件的文件夹......这将非常巨大,这样我就不会弄乱我的 .hbs 文件。
就像是
...pages.map(page => new HtmlWebpackPlugin({
template: 'hbs/pages/'+page,
filename: page,
data: myData.json
}))
会很好
干杯,格雷戈尔;)
解决方案
你可以使用 html-webpack-plugin 的 templateParameters 选项:
new HtmlWebpackPlugin({
templateParameters:require('path/to/data.json')
}),
templateParameters:允许覆盖模板中使用的参数
推荐阅读
- asp.net-mvc - 你调用的对象是空的。?
- c# - 递归 LINQ 查询函数中的嵌套索引
- c - 为什么系统提醒我运行时错误,即加载地址 0x602000000018 且对象空间不足
- sql - SQL 语句没有返回正确的数据
- postgresql - 如何使用烧瓶迁移迁移创建视图?
- java - Javac 不编译依赖于 jar 和类的 java 类
- javascript - 如何使用 ajax 从烧瓶中获取数据到我的模板?
- distributed-system - Dolphindb集群支持多个数据节点使用同一个磁盘目录?
- ios - 如何将可观察的元组元素与可观察的单个元素结合起来?
- java - 使用 RestHighLevelClient 的 ElasticSearch 批量插入错误