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

升级至Angular 13后无法导入区域设置模块,如何解决?

Angular 13+ 动态加载区域设置的正确方式

错误原因

Angular 13重构了@angular/common的包导出结构,原有的@angular/common/locales/${localeId}.js路径不再被官方导出,直接引用会触发"Package path ./locales is not exported"错误;而硬编码node_modules路径的方式既不规范,也会因为webpack模块解析逻辑导致找不到文件。

正确实现代码

替换为Angular 13+官方支持的动态加载路径:

private localeInitializer(localeId: string): Promise<any> {
  return import(
    /* webpackInclude: /(en|de|es|id)\.mjs$/ */
    `@angular/common/locales/global/${localeId}.mjs`
  ).then((module) => registerLocaleData(module.default));
}

如果使用async/await语法:

private async localeInitializer(localeId: string): Promise<void> {
  const module = await import(
    /* webpackInclude: /(en|de|es|id)\.mjs$/ */
    `@angular/common/locales/global/${localeId}.mjs`
  );
  registerLocaleData(module.default);
}

关键注意点

  • 路径必须使用@angular/common/locales/global/${localeId}.mjs,这是Angular 13+唯一支持的区域文件导出路径
  • webpack的webpackInclude正则要匹配.mjs后缀,因为Angular 13+默认输出ES模块格式
  • 不要直接写node_modules路径,依赖webpack的模块解析机制即可自动定位到正确文件
  • 若使用带地区的locale(如en-US),直接将localeId设为对应值即可,路径格式保持一致

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 00:03:23