angularesbuild

Dynamic import of dependencies in Angular with ESBuild


I have an application developed in Angular 17 and I have recently changed the builder for the new ESBuild compiler that Angular brings.

Everything has been fine except for importing libraries dynamically, which to my surprise, it seems that ESBuild does not support natively. As an example, this series of sentences:

export async function initialize(locale: string): Promise<void> {
    const localeMapped = CUSTOM_LOCALE_MAP[locale] || locale;

    try {
        await import(`dayjs/locale/${localeMapped}`);
    } catch (error) {
        console.error(error);
    }

    dayjs.locale(localeMapped);
}

Produce the following error:

enter image description here

What I find strange is that in Angular if they work lazy loads of modules or components (traditionally used in the router) so, does anyone know if there is a way to solve these dynamic loads of libraries?

Thanks


Solution

  • The issue is the dynamic import is using a non-static string. The bundler is not able to infer which file should be bundled.

    While this might have worked with Webpack and some custom comments, it was never officially supported.

    See this related issue