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

使用SSR运行Angular时遭遇$localize加载错误求助

Angular SSR启动时i18n $localize函数未加载的解决方法

问题描述

执行命令 npm run serve:ssr 启动Angular SSR服务时,出现以下错误:

throw new Error('It looks like your application or one of its dependencies is using i18n.\n' +
        ^

Error: It looks like your application or one of its dependencies is using i18n.
Angular 9 introduced a global `$localize()` function that needs to be loaded.
Please run `ng add @angular/localize` from the Angular CLI.
(For non-CLI projects, add `import '@angular/localize/init';` to your `polyfills.ts` file.
For server-side rendering applications add the import to your `main.server.ts` file.)
    at _global.$localize (/Users/jawad/Documents/jawad/truedealsweb/dist/server.js:68040:15)
    at Module../node_modules/@ng-bootstrap/ng-bootstrap/fesm2015/ng-bootstrap.js (/Users/jawad/Documents/jawad/truedealsweb/dist/server/main.js:134281:24)
    at __webpack_require__ (/Users/jawad/Documents/jawad/truedealsweb/dist/server/main.js:20:30)
    at Object../node_modules/@ng-bootstrap/ng-bootstrap/ng-bootstrap.ngfactory.js (/Users/jawad/Documents/jawad/truedealsweb/dist/server/main.js:148309:12)
    at __webpack_require__ (/Users/jawad/Documents/jawad/truedealsweb/dist/server/main.js:20:30)
    at Object../src/app/app.server.module.ngfactory.js (/Users/jawad/Documents/jawad/truedealsweb/dist/server/main.js:275302:12)
    at __webpack_require__ (/Users/jawad/Documents/jawad/truedealsweb/dist/server/main.js:20:30)
    at Object../src/main.server.ts (/Users/jawad/Documents/jawad/truedealsweb/dist/server/main.js:294702:37)
    at __webpack_require__ (/Users/jawad/Documents/jawad/truedealsweb/dist/server/main.js:20:30)
    at Object.0 (/Users/jawad/Documents/jawad/truedealsweb/dist/server/main.js:294731:18)

已在polyfills.ts中添加@angular/localize导入,但错误仍存在。

解决步骤

  • 在SSR入口文件添加localize初始化
    打开src/main.server.ts,在文件顶部添加以下导入语句:

    import '@angular/localize/init';
    

    SSR应用的server端代码不会自动加载polyfills.ts,必须在server入口文件中单独导入。

  • 确保安装@angular/localize依赖
    执行Angular CLI命令完成依赖安装和自动配置:

    ng add @angular/localize
    

    如果是非CLI项目,手动安装包:

    npm install @angular/localize
    
  • 清理缓存并重新构建

    • 删除已生成的dist文件夹:
      Mac/Linux:rm -rf dist
      Windows:rd /s /q dist
    • 重新构建SSR项目并启动:
      npm run build:ssr && npm run serve:ssr
      
  • 检查server模块配置
    确认AppServerModule在main.server.ts中正确引导,确保localize初始化代码在任何依赖i18n的模块加载前执行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 07:09:18