使用Handlebars.js时出现Uncaught ReferenceError: Handlebars未定义问题
解决Handlebars未定义的问题
当你用RequireJS加载Handlebars时,它默认不会把Handlebars挂载到全局window对象上,这就是你报错Uncaught ReferenceError: Handlebars is not defined的核心原因——你直接在全局作用域调用了Handlebars,但RequireJS是异步模块化加载,要么没加载完,要么没暴露全局变量。
给你一套可行的解决步骤:
- 先配置RequireJS的模块路径,指定jQuery和Handlebars的CDN地址,同时用
shim配置让Handlebars导出全局变量(兼容部分版本的Handlebars):
require.config({ paths: { 'jquery': 'https://code.jquery.com/jquery-3.6.0.min', 'handlebars': 'https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.7.7/handlebars.min' }, shim: { 'handlebars': { exports: 'Handlebars' } } });
- 然后通过
require方法加载这两个模块,在回调函数里使用Handlebars——只有当模块加载完成后,回调里的参数才会拿到对应的模块实例:
require(['jquery', 'handlebars'], function($, Handlebars) { // 这里写你的Handlebars业务代码,比如编译模板并渲染 const templateSource = $('#template').html(); const template = Handlebars.compile(templateSource); const data = {title: 'Handlebars测试', content: '终于不报错了!'}; $('#content').html(template(data)); });
- 注意:不要在
require回调外部直接使用Handlebars变量,所有依赖Handlebars的代码都要放在回调函数内部,确保模块已经加载完成。
另外,如果你用的是较新版本的Handlebars(4.0+),它本身已经支持AMD规范,shim配置可以省略,但保险起见加上也没问题。
内容的提问来源于stack exchange,提问作者pathikrit
相关产品推荐
相关产品推荐

