angularstorybookngx-translate

How to configure angular storybook for ngx-translate


I'm setting up an angular 18 UI library with standalone components. While configuring this for storybook 8 and the ngx-translate package, my json translation files (en.json, fr.json...) are not found.

My solution looks like:

projects/
  └── my-angular-library/
    ├── src/
    │   ├── lib/
    │   ├── assets/
    │   │   └── i18n/
    │   │       ├── en.json
    │   │       ├── fr.json
    │   │       └── ...
    │   └── public-api.ts
    └── ...

My translate-config.module.ts

import { NgModule } from '@angular/core';
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { HttpClient, HttpClientModule } from '@angular/common/http';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, '/assets/i18n/', '.json');
}

@NgModule({
  imports: [
    HttpClientModule,
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      },
      defaultLanguage: 'en'
   })
  ],
  exports: [TranslateModule]
})
export class TranslateModuleConfig { }

The component where I use the translation pipe and import my config module. (Note the import of the translation pipe too)

@Component({
  selector: 'my-component',
  standalone: true,
  imports: [CommonModule, TranslateModuleConfig, TranslatePipe],
  template: `<div>{{ 'greeting' | translate }}</div>`,
})
export class MyComponent {
  ...

This results in not finding my json language files. I tried to add some staticDirs: ['../public', '../static', '../src/assets'] in the main.ts file of Storybook, but that didn't work either.


Solution

  • Seems that you need to alter your angular.json file too. In the angular.json file, make sure to include the assets folder in the build configuration for your library:

    "projects": {
      "my-angular-library": {
        "architect": {
          "build": {
            "options": {
              "assets": [
                "projects/my-angular-library/src/assets"
              ]
            }
          }
        }
      }
    }