Search code examples
angularwebpackpackageinternationalization

async import with configurable path within npm library


I have a module that loads messages for angular i18n. The crucial part looks like this:

const lang = 'en';
const pathToLocales = 'path/to/locales';
const localeTranslationsModule = await import(`${pathToLocales}/messages.${lang}.json`);
// Load translations for the current locale at run-time
loadTranslations(localeTranslationsModule.default.translations);

This works perfectly fine as long as it is whithin the angular app. The path here would be something like apps/my-app/i18n where the message files are located.

Since I need this in several apps and I don't want the code to be in every single app I decided to extract this into a library @my-org/i18n. Now when I am using the module from the @my-org/i18n and put the path/to/locales as parameter, it cannot find the path.

My guess is, that the path cannot be resolved relative to node_modules. But how would one then configure a path like that?


Solution

  • Since you are using webpack dynamic expression syntax you must start the path with a static string and not a dynamic one, because webpack needs to know where to start. Something like:

    import(`./locale/${language}.json`)
    

    Checkout this documentation