1 | initial version |
Install the nestjs-i18n
package by running the command npm install nestjs-i18n
.
Import the I18nModule
into the root AppModule
and configure it. For example:
import { I18nModule } from 'nestjs-i18n';
import * as path from 'path';
@Module({
imports: [
I18nModule.forRoot({
defaultLanguage: 'en',
fallbackLanguage: 'en',
parserOptions: {
path: path.join(__dirname, '/i18n/'),
watch: false,
},
}),
],
})
export class AppModule {}
This sets the default language to English and sets the fallback language to English as well if another language header is not accepted. It also specifies the location of the translation files in the /i18n/
directory.
main.ts
file. For example:import { I18nMiddleware } from 'nestjs-i18n';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(I18nMiddleware);
await app.listen(3000);
}
bootstrap();
This sets up the middleware to accept the Accept-Language
header and check if the language specified in the header is supported by the application.
/i18n/en.json
:{
"hello": "Hello World!"
}
TranslateService
in your controllers or services to translate text. For example:import { Controller, Get } from '@nestjs/common';
import { TranslateService } from 'nestjs-i18n';
@Controller()
export class AppController {
constructor(private readonly translateService: TranslateService) {}
@Get()
async getHello(): Promise<string> {
return await this.translateService.translate('hello');
}
}
This translates the "hello" key to the value "Hello World!" in the specified language.
Accept-Language
header set to a supported language. The response should be in the specified language.