You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular 12中使用Handlebars?升级后报错该如何解决?

解决方案

报错根因

Angular 12默认使用Webpack 5作为打包工具,Handlebars官方发布的npm包主入口是CommonJS格式的源文件,内部包含动态require语法,无法被Webpack 5静态解析,所以出现上述报错。

方案1:直接修改导入路径(最简单)

  • 将原有导入语句替换为指向预构建UMD版本的路径:
    import * as handlebars from 'handlebars/dist/handlebars.min.js';
  • 若缺少TypeScript类型定义,执行命令安装类型包:
    npm install @types/handlebars --save-dev
    该方案改完直接生效,无需其他配置。

方案2:配置TS路径别名(无需修改原有导入语句)

如果不想改动项目中已有的import * as handlebars from 'handlebars'语句,可以通过配置别名实现:

  1. 打开项目根目录下的tsconfig.json,在compilerOptions节点下添加如下配置:
"paths": {
  "handlebars": [
    "./node_modules/handlebars/dist/handlebars.min.js"
  ]
}
  1. 同方案1,若缺少类型定义则安装@types/handlebars包即可。

注意事项

之前你将node_modules/handlebars/dist/handlebars.min.js添加到angular.json的scripts数组中无效的原因是:该配置只会将Handlebars挂载到全局window对象,你代码中通过ESModule导入的仍然是Handlebars包主入口指向的有问题的lib目录文件,所以报错无法解决。如果要使用全局挂载的方式,需要删除代码中的import语句,直接使用window.Handlebars调用即可,更推荐上述模块化导入的方案。

如果编译时出现CommonJS依赖警告,可以在angular.json中对应项目的architect > build > options节点下添加:

"allowedCommonJsDependencies": ["handlebars"]

即可消除警告。

内容的提问来源于stack exchange,提问作者sergenn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:00:05