Dynamic loading of locale in Angular 5 using Angular CLI

Angular 5 offers a solution for loading i18n locale dynamically using registerLocaleData

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

I am interested in loading the locale based on a dynamic setting, such as one stored in localStorage. I tested loading a single locale (fr) first:

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

This approach works without any issues.

Next, I tried loading the locale based on a value from localStorage like this:

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

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

Surprisingly, this method also works well and successfully loads the desired locale. However, when building the project using Angular CLI, since it doesn't know which locale to bundle at build time, it bundles all of them. While this is acceptable, the build process generates a warning for each loaded locale:

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 have attempted to include the locale *.ts files and exclude *.map files but the build process seems to disregard them.

Here 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"
  ]
}

To enable dynamic imports, TypeScript requires esnext as the module setting. It does not function properly with es2015.

Answer №1

To resolve the problem, it appears that importing only the *.js files is the solution, as shown below:

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

You don't have to specify which files to include or exclude in tsconfig.app.json

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Downloading Files in Angular Using HttpClient - Extracting File Names from the Server Response

I am currently working on retrieving a File from an API URL. My goal is to display this uploaded file in an input field along with its name. To achieve this, I have implemented the following service function: getDocument(): Observable<Blob> { c ...

Can you explain the significance of subscribing and subscribe in Angular? Also, clarify when is the appropriate time to use them - in the constructor or ngOnInit method

After encountering numerous instances of code containing the subscribe method in Angular, I began to wonder about the consequences of not utilizing them. What are we potentially missing out on? I've noticed that all the code snippets using subscribe ...

How can I make a div's height match that of another div?

I am curious about adjusting the height of a div based on its content. In this case, I have the following HTML structure: div.Pantalla { background-image: url("https://cdn.pixabay.com/photo/2015/07/11/23/02/plane-841441_1280.jpg"); background-size ...

Updating Facebook meta tags dynamically in Angular 4 to enhance Open Graph integration

Is there a way to dynamically update meta tags for Facebook/Whatsapp share dialog? I recently upgraded my angular 2 application to angular 4 in order to utilize the Meta service and update meta tags dynamically once data is retrieved from an API. Within ...

Incorporate a CSS class name with a TypeScript property in Angular version 7

Struggling with something seemingly simple... All I need is for my span tag to take on a class called "store" from a variable in my .ts file: <span [ngClass]="{'flag-icon': true, 'my_property_in_TS': true}"></span> I&apos ...

A Typescript function will only return a partial if the parameter passed into it is also

I have a function that takes a camelCase object and returns the same object in snake_case format. // Let's consider these types interface CamelData { exempleId: number myData:string } interface SnakeData { exemple_id: number my_data: stri ...

Uncertainty surrounding refinement in Typescript

I've been diving into the book Programming TypeScript, and I'm currently stuck on understanding the concept of refinement as shown in this example: type UserTextEvent = { value: string; target: HTMLInputElement }; type UserMouseEvent = { value: [ ...

Guidelines for creating a binary release of Node.js with native modules

Currently, I am in the midst of exploring the world of Node.js projects, delving into different bundlers and various other components. One interesting concept that came to mind is the idea of bundling Node.js into a single binary for Linux, macOS, or Windo ...

How is it possible for TypeScript to enable the importing of dependencies that it ultimately cannot utilize during runtime?

Take a look at my sample project by following this link: https://github.com/DanKaplanSES/typescript-stub-examples/tree/JavaScript-import-invalid I have developed a file named main.ts: import uuid from "uuid"; console.log(uuid.v4()); While type ...

Leveraging the 'this' keyword in TypeScript

In my Javascript class, I used the 'this' keyword as shown below: if (this[this.props.steps[i].stepId].sendState !== undefined) { this.setState({ allStates: { ...this.state.allStates, [thi ...

The FileSaver application generates a unique file with content that diverges from the original document

I'm attempting to utilize the Blob function to generate a file from information transmitted via a server call, encoded in base64. The initial file is an Excel spreadsheet with a length of 5,507 bytes. After applying base64 encoding (including newlines ...

Expand the size of the imported gltf model within Three.js

After successfully loading a 3d model with a gltf extension using the GLTFLoader in Three.js, I encountered a new challenge. I needed to adjust the dimensions of the model dynamically when the window is resized, based on the values of window.innerWidth and ...

Running Jest tests with TypeScript involves executing the tests twice: once for TypeScript files and once for JavaScript files

I’ve recently started writing tests using TypeScript and Jest, but I’m running into an issue where the tests are being executed twice – once for the TS files and then again for the compiled JS files. While the TypeScript tests are passing without an ...

"In TypeScript, when something is undefined, it means its value

I am currently working on a class with code to help manage a database. export class DatabaseHelper { public browserID : number; private ConfigID = 17; } Within this class, I am attempting to access the value of ConfigID SetBrowserID() { ...

Regular pattern with Kubernetes cluster endpoint utilizing either IP address or fully qualified domain name

In my Angular/typescript project, I am working on building a regex for a cluster endpoint that includes an IP address or hostname (FQDN) in a URL format. For instance: Example 1 - 10.210.163.246/k8s/clusters/c-m-vftt4j5q Example 2 - fg380g9-32-vip3-ocs.s ...

Set the default value for a form control in a select dropdown using Angular

I've been struggling to figure out how to mark an option as selected in my select element, but I haven't had any luck. I've tried multiple solutions from the internet, but none of them seem to be working for me. Does anyone out there have ...

There seems to be an issue with the compatibility between typescript and the current version (4.17.14) of the express-serve-static

Using "@types/express-serve-static-core": "4.17.13", the augmentation of express-serve-static-core is functioning properly: import { Request, Response, NextFunction } from 'express' import { PrismaClient } from '@prisma/c ...

Assign a variable to set the property of a class

Could something similar to this scenario be achievable? const dynamicPropName = "x"; class A { static propName = 1 // equivalent to static x = 1 } A[dynamicPropName] // will result in 1 or would it need to be accessed as (typeof A)[dynamicPropN ...

Angular 2: Applying a class to a specific element by referencing its id

I am trying to figure out how to add a class to an element with a specific id in Angular 2. In regular JavaScript, you can do it like this, but I need help translating this into Angular 2: document.getElementById("MyElement").className += " active"; Cur ...

Tips for implementing pagination on a large JSON file without traditional pagination controls

Looking for the best way to implement pagination in a NextJs app that loads products from a local JSON file? This JSON file doesn't have any page properties, so the only option is to limit the number of products shown by using slice: {Object ...