Angular 5 在运行时使用 Angular CLI 加载语言环境 [英] Angular 5 loading locale at runtime with Angular CLI

查看:28
本文介绍了Angular 5 在运行时使用 Angular CLI 加载语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Angular 5 提供了一种使用 registerLocaleData

Angular 5 provides a way to load i18n locale at runtime using registerLocaleData

https://angular.io/guide/i18n#i18n-pipes

我想根据设置(例如存储在 localStorage 中)动态加载语言环境.我的第一个测试是加载单个语言环境 (fr):

I would like to load the locale dynamically based on a setting (for example stored in localStorage). My first test was to load a single locale (fr):

import(`@angular/common/locales/fr`).then(locale => {
    registerLocaleData(locale.default);
});

这很好用.

基于存储在 localStorage 中的值加载时,如下所示:

When loading based on a value stored in localStorage, like this:

const localeName = localStorage.getItem('locale') || 'en';

import(`@angular/common/locales/${localeName}`).then(locale => {
    registerLocaleData(locale.default);
});

它也可以工作,并且成功加载了语言环境.当使用 Angular CLI 构建项目时,由于在构建时它不知道要捆绑哪个语言环境,它会将所有语言环境都捆绑在一起,这很好.唯一的问题是构建过程会为其加载的每个区域设置发出警告:

It also works, and the locale is loaded successfully. When bulding the project using Angular CLI, since at build time it doesn't know which locale to bundle, it bundles all of them, which is fine. The only issue is that the build process gives a warning for every locale it loads:

模块构建失败:错误:node_modules\@angular\common\locales\af-NA.d.ts 不是编译输出.有关详细信息,请查看其他错误消息.

Module build failed: Error: node_modules\@angular\common\locales\af-NA.d.ts is not part of the compilation output. Please check the other error messages for details.

./node_modules/@angular/common/locales/af-NA.js.map 中的警告模块解析失败:意外令牌 (1:10)您可能需要一个合适的加载器来处理这种文件类型.

WARNING in ./node_modules/@angular/common/locales/af-NA.js.map Module parse failed: Unexpected token (1:10) You may need an appropriate loader to handle this file type.

我已经尝试包含语言环境 *.ts 文件并排除 *.map 文件,但它似乎没有选择它们.

I already tried to include the locale *.ts files and exclude *.map files but it doesn't seem to pick them up.

这是我的tsconfig.app.json:

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "baseUrl": "./",
    "module": "esnext",
    "types": []
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts",
    "../node_modules/@angular/common/locales/**/*.map"
  ],
  "include": [
    "**/*",
    "../node_modules/@angular/common/locales/**/*.ts"
  ]
}

TypeScript 需要 esnext 作为模块来进行动态导入.使用 es2015 它不起作用

TypeScript needs esnext as module to make the dynamic import work. With es2015 it doesn't work

推荐答案

只导入 *.js 文件似乎可以解决问题,如下所示:

Importing only the *.js files seems to fix the issue, like this:

import(`@angular/common/locales/${localeName}.js`).then(locale => {
   registerLocaleData(locale.default); 
});

无需在tsconfig.app.json中包含或排除文件

No need to include or exclude files in tsconfig.app.json

这篇关于Angular 5 在运行时使用 Angular CLI 加载语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆