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.Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-05-09 11:00:00 +0000
Seen: 8 times
Last updated: Nov 05 '22
How can I utilize a view above and between bottom tabs in React Native Navigation?
How can the header label be made dynamic in react-table?
How to retrieve header and body data in Next.js using prefetch function?
How do I add a search bar to the header of my Square Space 7.1 website?
How can I use Office Script to delete all rows in Excel except for the first header row?