Label Module Provider

Want to localize labels and reuse them across different pages? The Label Module Provider serves file-based labels as ES modules, and it shows different translations of each label depending on the user’s locale.

To determine the user’s locale, the Label Module Provider evaluates these resources in this order:

  1. The locale path parameter in the request
  2. The Accept-Language header in the request
  3. The default locale set by the runtime

Create Reusable Labels 

In your project’s src directory, add a labels folder. For each supported locale, create a JSON file that contains all the labels you want to use. The name of each file should be the all-lowercase locale code corresponding to the language and region of its labels. For example, if you have labels for the fr-FR locale, put them in a file named fr-fr.json.

If the Label Module Provider can’t find a label file for a requested language and region code, it looks for a file that corresponds to only the requested language. For example, if a user requests en-US labels but you don’t have an en-us.json file, the module provider looks for an en.json file as a fallback.

Sample Project Directory
1src/
2  ├── assets/
3  ├── labels/
4  │   ├── en.json       // English
5  │   ├── es.json       // Spanish
6  │   ├── it.json       // Italian
7  │   └── fr-fr.json    // French (France)
8  ├── labelHandler.ts   // route handler for template translations
9  ├── layout.html       // static layout template
10  └── modules/
11lwr.config.json
12package.json

Here’s an example of a file with labels for the English (en) language.

src/labels/en.json
1{
2    "title": "Translation",
3    "home": {
4        "greeting": "Welcome"
5    },
6    "animal": {
7        "cat": "Cat",
8        "dog": "Dog"
9    }
10}

The same labels for the French (fr) language and country of France (FR) are in a separate file.

src/labels/fr-fr.json
1{
2    "title": "Traduction",
3    "home": {
4        "greeting": "Bienvenu"
5    },
6    "animal": {
7        "cat": "Chat",
8        "dog": "Chien"
9    }
10}

Add the Label Module Provider 

To import the package for this module provider (@lwrjs/label-module-provider), run this code in your terminal. This also adds a dependency on @lwrjs/label-module-provider to your project’s package.json.

1npm install @lwrjs/label-module-provider

Then, register the module provider in lwr.config.json. Remember to include all the default module providers in the moduleProviders array.

lwr.config.json
1{
2  "moduleProviders": [
3    "@lwrjs/label-module-provider",       // Add the Label Module Provider
4    "@lwrjs/app-service/moduleProvider",  // Default provider
5    "@lwrjs/router/module-provider",      // Default provider
6    "@lwrjs/lwc-module-provider",         // Default provider
7    "@lwrjs/npm-module-provider",         // Default provider
8    "@lwrjs/module-registry/externals-module-provider"    // Default provider
9  ]
10}

In the same config file, add a route handler to the app route.

lwr.config.json
1{
2    "routes": [
3        {
4            "id": "labels",
5            "path": "/",
6            "routeHandler": "$rootDir/src/labelHandler.ts"
7        }
8    ]
9}

Optional: Configure the Label Module Provider 

In lwr.config.json, you can set a package specifier for importing labels and customize the filepath of the label files.

  • provideDefault - When true, the module provider returns the label reference as the value for any label it can’t find. When false, the module provider returns undefined for labels it can’t find. This lets any module providers called afterward attempt to resolve the request.
  • labelDirs - An array of one or more label package namespaces and their locations in the project directory.
lwr.config.json
1{
2    "moduleProviders": [
3        // Start of Label Module Provider configuration
4        [
5            "@lwrjs/label-module-provider",
6            {
7                "provideDefault": true,
8                "labelDirs": [
9                    {
10                        "dir": "$rootDir/src/labels",   // Filepath
11                        "package": "@my/label"          //
12                    }
13                ]
14            }
15        ],
16        // End of Label Module Provider configuration
17         "@lwrjs/app-service/moduleProvider",
18    ]
19}

If you don’t specify a value for dir or package, the module provider uses the following configuration by default.

lwr.config.json
1{
2    "provideDefault": false,
3    "labelDirs": [
4        {
5            "dir": "$rootDir/src/labels",
6            "package": "@salesforce/label"
7        }
8    ]
9}

Import Labels into a Component 

After you create your label files and configure the Label Module Provider, you can import labels into your components.

Here’s an example of an app that displays a localized string (greeting) on its homepage. The Label Module Provider returns the label value from the file corresponding to the requested locale.

app.html
1<!-- app.html -->
2<template>
3    <h1>{greeting}</h1>
4</template>
app.ts
1import { LightningElement } from 'lwc';
2import GREETING from '@my/label/home.greeting';
3
4export default class LocalizedApp extends LightningElement {
5    greeting = GREETING;
6}

In this example:

  • import GREETING from '@my/label/home.greeting' determines the language of the text that’s displayed on the homepage.
  • @my/label is the package namespace configured through the Label Module Provider
  • home.greeting is the label reference in the label files. It’s in the format of a property selector for label JSON file.

Import Labels into a Template 

Templates can’t access the Label Module Provider. To pass translated strings into static templates, use a route handler. Templates have access to the viewParams returned by the route handler.

labelHandler.ts
1import type { HandlerContext, LocalizedViewRequest, RouteHandlerViewResponse } from '@lwrjs/types';
2
3const DEFAULT_LOCALE = 'en';
4
5function getViewParams(locale: string, rootDir: string): { title: string; language: string } {
6    // Get the translated string from the file system, a database, etc.
7}
8
9// Return translated strings to be used in the layout template
10export default function translationRouteHandler(
11    viewRequest: LocalizedViewRequest,
12    context: HandlerContext,
13): RouteHandlerViewResponse {
14    const locale = viewRequest.locale || DEFAULT_LOCALE;
15    const params = getViewParams(locale, context.rootDir);
16    return {
17        view: {
18            // This layout template uses the viewParams
19            layoutTemplate: '$rootDir/src/layout.html',
20        },
21        viewParams: {
22            // available as {{title}} or {{page.title}} in the layout template
23            title: params.title,
24            // available as {{language}} in the layout template
25            language: params.language,
26        },
27    };
28}
src/layout.html
1<!doctype html>
2<html lang="{{language}}">
3    <head>
4        <title>{{title}}</title>
5    </head>
6    <body>
7        <example-app></example-app>
8        {{{lwr_resources}}}
9    </body>
10</html>

Developer Preview Feature

Feature is available as a developer preview. Feature is not generally available unless or until Salesforce announces its general availability in documentation or in press releases or public statements. All commands, parameters, and other features are subject to change or deprecation at any time, with or without notice. Do not implement functionality developed with these commands or tools.