In some cases, you may need to include translations within your npm libraries, especially in a monorepo environment. This allows you to keep translation files inside the library's folder and package them together. However, loading translation files directly from the library can be challenging for two main reasons:
The applicationโs public directory isn't directly accessible.
Webpack dynamic imports donโt work with libraries.
To overcome these issues, the only option is to load the translation files from the application's public folder. This means you would need to manually copy the translation files from the library to the application's translation folder, which can be repetitive and error-prone.
This is where the Scoped Library Extractor tool comes in, which automates this process for you.
Example Setup
Let's consider a monorepo with the following structure:
Here, we have a core library with its own translation files located under projects/core/src/lib/i18n. To use these translations in our application, we need to configure the libraryโs translations in the CoreModule.
1
Declare the Translation Scope
In the CoreModule, provide the scope for the translations:
Now, run the script to extract the translation files from the library and copy them to the main project's translation folder:
pnpmtransloco:extract-scoped-libs
This script will:
Extract the translation files from the library.
Copy them to the main project's src/assets/i18n folder.
Add the libraryโs translation files to .gitignore (use the --skip-gitignore flag if you want to skip this step).
Join Strategies
The tool supports two strategies for handling translations:
Default Strategy: The translation files from the library will be copied individually into the main project's translation folder.
Join Strategy: All translation files from the library will be combined into a single file (e.g., en.vendor.json), which can then be loaded alongside the main translation files.
To use the Join Strategy, modify the package.json of the library: