使用Angular CLI在运行时Angular 5加载区域设置 [英] Angular 5 loading locale at runtime with Angular CLI

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

问题描述

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

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

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