Angular 5 provides a way to load i18n locale at runtime using registerLocaleData
https://angular.io/guide/i18n#i18n-pipes
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);
});
This works fine.
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);
});
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:
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.
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.
I already tried to include the locale *.ts files and exclude *.map files but it doesn't seem to pick them up.
This is my 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 needs esnext as module to make the dynamic import work. With es2015 it doesn't work
Importing only the *.js files seems to fix the issue, like this:
import(`@angular/common/locales/${localeName}.js`).then(locale => {
registerLocaleData(locale.default);
});
No need to include or exclude files in tsconfig.app.json
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With