Bha*_*oni 5 handlebars.js webpack handlebarshelper
我在我的项目中使用 Handlebars,并使用 webpack 捆绑模板。我正在使用handlebars-loader编译模板。我在创建一个小助手时遇到了问题。当我在模板中使用 helper 时,Webpack 会显示此错误:
You specified knownHelpersOnly, but used the unknown helper withCurrentItem - 5:4
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
网络包:
{
test : /\.(tpl|hbs)$/,
loader : "handlebars-loader?helperDirs[]=" + __dirname + "templates/helpers"
// use : 'handlebars-loader?helperDirs[]=false' + __dirname + 'templates/helpers'
},
Run Code Online (Sandbox Code Playgroud)
助手(项目/模板/助手/withCurrentItem.js):
export default function (context, options) {
const contextWithCurrentItem = context
contextWithCurrentItem.currentItem = options.hash.currentItem
return options.fn(contextWithCurrentItem)
}
Run Code Online (Sandbox Code Playgroud)
模板文件(project/templates/products.tpl):
{{> partials/filters}}
<ul class="u-4-5">
{{#each data.products}}
{{> partials/product}}
{{withCurrentItem ../styles currentItem=this}}
{{/each}}
</ul>
Run Code Online (Sandbox Code Playgroud)
我试图解决这个问题并在互联网上搜索,但我找不到任何东西。这是我尝试过的:
将helperDirs[]查询参数添加到加载器:
loader : "handlebars-loader?helperDirs[]=" + __dirname + "templates/helpers"
将 helpers 目录路径添加到resolve.moduleswebpack 配置文件的属性
可悲的是,它们都不起作用。
对我来说,这些方法都不起作用。我使用runtime选项创建了自己的 Handlebars 实例(感谢此评论):
webpack.config.js
module: {
rules: [
{
test: /\.(handlebars|hbs)$/,
loader: 'handlebars-loader',
options: {
runtime: path.resolve(__dirname, 'path/to/handlebars'),
},
},
Run Code Online (Sandbox Code Playgroud)
路径/to/handlebars.js
const Handlebars = require('handlebars/runtime');
Handlebars.registerHelper('loud', function(aString) {
return aString.toUpperCase();
});
module.exports = Handlebars;
Run Code Online (Sandbox Code Playgroud)
webpack@3.5.5和handlebars-loader@1.5.0:
{
test: /\.hbs$/,
loader: 'handlebars-loader',
options: {
helperDirs: path.join(__dirname, 'modules/helpers'),
precompileOptions: {
knownHelpersOnly: false,
},
},
},
Run Code Online (Sandbox Code Playgroud)
2021 年更新:也适用于webpack@4+。
| 归档时间: |
|
| 查看次数: |
5072 次 |
| 最近记录: |