我正在编写一个自定义webpack加载器。
它将把手转换为车把模板,但是在导出对象而不是函数时遇到了一个奇怪的问题。
基本上这很好用:
'module.exports = (Handlebars).template(' + source + ');'
失败:错误(The partial foo could not be compiled when running in runtime-only mode
):
'module.exports.compile = (Handlebars).template(' + source + ');'
有什么不同?
答案 0 :(得分:0)
module.exports = () => {
compile: handlebars.template(templateSpec),
attributes: myFrontMatterData
}
这不起作用,因为它不是有效的JavaScript,你应该得到SyntaxError: Unexpected token :
。当你使用花括号时,箭头函数有一个常规块Function body,它不是隐式返回一个对象,而是像一个常规函数。使用块体,正确的功能是:
module.exports = () => {
return {
compile: handlebars.template(templateSpec),
attributes: myFrontMatterData
}
}
您仍然可以使用对象文字作为隐式返回,但由于大括号是为信号块保留的,因此您需要将对象文字包装在括号中(另请参阅Returning object literals):
module.exports = () => ({
compile: handlebars.template(templateSpec),
attributes: myFrontMatterData
})
答案 1 :(得分:0)
路过的任何人都解决了这个问题。
var slug = template ?
'var Handlebars = require(' + JSON.stringify(runtimePath) + ');\n'
+ 'function __default(obj) { return obj && (obj.__esModule ? obj["default"] : obj); }\n'
+ 'var fn = Handlebars.template(' + template + ');\n'
+ 'fn.attributes = ' + JSON.stringify(source.attributes) + ';\n'
+ 'module.exports = fn;' :
'module.exports = function(){return "";};';