How to dynamically import a date-fns language module in an Angular Ionic application

Discussão em 'Angular' iniciado por peterc, Agosto 5, 2025.

  1. peterc

    peterc Guest

    I am replacing moment with date-fns in my Ionic Angular project.

    I run with many possible languages, so did not want to statically import them all, and make the bundle bigger.

    I am trying the following...

    private async setLocale(lang: string): Promise<void> {
    try {
    if (!lang) {
    return;
    }

    const localeMap: Record<string, string> = {
    en: 'enAU',
    // eslint-disable-next-line @typescript-eslint/naming-convention
    'en-US': 'enUS',
    // eslint-disable-next-line @typescript-eslint/naming-convention
    'en-AU': 'enAU',
    fr: 'fr',
    de: 'de',
    };

    const localeKey = localeMap[lang] || lang;

    const localeModule = await import(
    /* webpackChunkName: "date-fns-locale-[request]" */
    `date-fns/locale/${localeKey}`
    );
    const locale = localeModule.default;
    setDefaultOptions({ locale });
    } catch (error) {
    this.logger.error(
    `${MODULE_NAME}.setLocale: Error setting locale to ${lang}: ${Utils.unknownTypeToString(
    error
    )}`
    );
    }
    }


    However I get the exception..

    [​IMG]

    I am not 100% where the await import is trying to load from; surely not node_modules, which will not be present in the deployed bundles.

    The string I am passing in us just en-US.

    Anyone know what could be wrong here, or how I can diagnose?

    Thanks in advance

    Continue reading...

Compartilhe esta Página