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

Utilize Lambda Layer to seamlessly share interfaces/types across Lambda Functions

I have a lambda layer file that contains an enum definition (which will be used in various lambda functions) as shown below: exports enum EventTypes { Create, Delete, Update, } Initially, everything was working well as I tested ...

Disable and grey out the button while waiting for the Observable to broadcast successfully

component.html <button mat-raised-button color="primary" type="submit"> <mat-icon>account_box</mat-icon> <span *ngIf="!loading">&nbsp;&nbsp;&nbsp;Register</span> <span * ...

Issue with TypeScript when using destructuring on an object

When attempting to destructure data from an object, I encountered the error message Property XXXX does not exist on type unknown. This issue arose while using React Router to retrieve data. let {decoded, reasonTypes, submissionDetails} = useRouteLoaderDa ...

Updating state in React without providing a key prop is a common issue, especially when

Currently, I am working on implementing a Radio Group where I want the radio button's checked value to update when another button is clicked. In the example provided below, it seems that the desired effect can only be achieved using the "key" prop. Is ...

Encountering an ECONNREFUSED error upon upgrading from Next.js 12 to 13

After upgrading from Nextjs 12 to 13, I am experiencing issues where every time I try to run the application, I encounter ECONNREFUSED to my local host but the port seems to keep changing. This results in the application not rendering properly. > <a ...

Using react-confetti to create numerous confetti effects simultaneously on a single webpage

I'm looking to showcase multiple confetti effects using the react-confetti library on a single page. However, every attempt to do so in my component seems to only display the confetti effect on the last element, rather than all of them. The canvas fo ...

Error: R3InjectorError(Environment Injector) - Unable to inject MsalService into MsalService due to NullInjectorError: MsalService provider not found

Can someone help me understand why I am getting this error when trying to integrate MSAL into my Angular app? ERROR NullInjectorError: R3InjectorError(Environment Injector)[MsalService -> MsalService]: NullInjectorError: No provider for MsalService! ...

IntelliJ is unable to locate the scss import when using the includePaths option in stylePreprocessorOptions

Having trouble with IntelliJ 2019.2.2 Ultimate not detecting scss imports from stylePreprocessorOptions - includePaths Here is the directory structure: https://i.stack.imgur.com/SQEDT.png In my angular.json file, I have specified: "stylePreprocessorOpt ...

Determine in React whether a JSX Element is a descendant of a specific class

I am currently working with TypeScript and need to determine if a JSX.Element instance is a subclass of another React component. For instance, if I have a Vehicle component and a Car component that extends it, then when given a JSX.Element generated from ...

Getting started with testing in Angular 2

When I first started coding my app, unit tests were not on my mind. Now, I realize the importance and need to write them. However, while attempting to write tests using Jasmine only, I encountered an error when trying to import components - "system is no ...

What is the best way to prevent jest.mock from being hoisted and only use it in a single jest unit test?

My goal is to create a mock import that will be used only in one specific jest unit test, but I am encountering some challenges. Below is the mock that I want to be restricted to just one test: jest.mock("@components/components-chat-dialog", () ...

What is the best way to refine the dataSource for a table (mat-table) using ngx-daterangepicker-material?

I am facing a new challenge and feeling unsure about how to approach it. The issue at hand is filtering a table based on the date range obtained through the ngx-daterangepicker-material library. This library triggers events that provide a start date and a ...

Accessing Next and Previous Elements Dynamically in TypeScript from a Dictionary or Array

I am new to Angular and currently working on an Angular 5 application. I have a task that involves retrieving the next or previous item from a dictionary (model) for navigation purposes. After researching several articles, I have devised the following solu ...

What is the most effective way to receive all values sent to an Observer upon a new subscription?

I have an observer that receives various values emitted to it at different times. For instance sub = new Subject<any>(); sub.next(1); sub.next(2); sub.next(3); #hack 1 sub.next(4); sub.next(5); sub.next(6); #hack 2 If there is a ...

HammerJS swipe functionality does not seem to be functioning properly on elements that have the overflow CSS

UPDATE: The code snippet works smoothly when embedded in the question, but encounters issues when edited. This led me to discover that the problem lies with underlying containers that require scrolling... After testing it on my phone, I found that Hammer f ...

A guide on specifying the data type for functions that receive input from React Child components in TypeScript

Currently, I am faced with the task of determining the appropriate type for a function that I have created in a Parent Component to retrieve data from my Child Component. Initially, I resorted to using type: any as a solution, although it was not the corr ...

Tips for including a sequelize getter in a model instance?

I'm currently struggling to add a getter to the name field of the Company model object in my project. Despite trying various approaches, I haven't had any success so far. Unfortunately, I also couldn't find a suitable example to guide me thr ...

Tips for creating Junit tests for a CDK environment

As a newcomer to CDK, I have the requirement to set up SQS infrastructure during deployment. The following code snippet is working fine in the environment: export class TestStage extends cdk.Stage { constructor(scope: cdk.Construct, id: string, props: ...

Leveraging Shared and CoreModule in Ionic

In the recommended styleguide found at https://angular.io/guide/styleguide#core-feature-module, it is suggested to implement a SharedModule and CoreModule in an Angular application. I am curious if utilizing these modules would also be beneficial in an Io ...

What is the best way to capture the inputs' values and store them accurately in my object within localStorage?

Is there a more efficient way to get all the input values ​​and place them in the appropriate location in my object (localStorage) without having to individually retrieve them as shown in the code below? Below is the function I currently use to update ...