webpack引入handlebars报错'You must pass a string or Handlebars AST to Handlebars.compile'

时间:2023-03-10 01:46:44
webpack引入handlebars报错'You must pass a string or Handlebars AST to Handlebars.compile'

背景: webpack作为一个部分替代打包工具和模块化工具的优秀选择出现,作为尝试,也为了构建自己习惯的前端开发方式,我尝试了将webpack和自己常用handlebars模板引擎结合.整体项目背景为: koa + webpack + handlebars + jquery 这样的结构.

webpack引入handlebars报错'You must pass a string or Handlebars AST to Handlebars.compile'

尝试: 使用sixstone脚手架生成的项目结构;在静态资源目录public下放置webpack.config.js以及核心js文件及模板tpl/xx.hbs;在运行webpack --progress --colors --watch后引入的js文件会一直报错.

报错信息:

"You must pass a string or Handlebars AST to Handlebars.compile. You passed function ret(context) {↵ var options ……

错误分析:

Handlebars.compile方法插入的参数是一个function而不是string,(打印出的结果);var addUserTpl = require('../tpl/add-user.hbs');猜测可能是把需要返回的字符串放到了一个方法里.

解决方案:

var addUserTpl = require('../tpl/add-user.hbs');

替换为

var addUserTpl = require('../tpl/add-user.hbs')();

验证想法: 打开build后的结果.

webpack引入handlebars报错'You must pass a string or Handlebars AST to Handlebars.compile'

虽然不明白具体实现,但很明显的看到一个module.exprots = function(){return 'xx' };