Nodejs Nestjs国际化插件nestjs-i18n的使用
Nodejs Nestjs国际化插件nestjs-i18n的使用nestjs-i18n
是一个在 NestJS 项目中实现国际化(i18n)功能的插件。以下是如何安装和配置 nestjs-i18n
的步骤:
安装
首先,你需要安装 nestjs-i18n
及其依赖项:
npm install @golevelup/nestjs-i18n i18n
配置
接下来,你需要在你的 NestJS 应用中配置 nestjs-i18n
。
- 创建配置文件:你可以在项目根目录下创建一个
i18n.config.ts
文件来配置nestjs-i18n
:
import { I18nConfig } from '@golevelup/nestjs-i18n';
export default <I18nConfig> {
path: './src/i18n/__lng__/__ns__.json', // 路径模式
fallbackLanguage: 'en', // 默认语言
};
- 注册模块:在你的主模块(通常是
app.module.ts
)中导入并配置I18nModule
:
import { Module } from '@nestjs/common';
import { I18nModule } from '@golevelup/nestjs-i18n';
@Module({
imports: [
I18nModule.forRoot({
config: require('./i18n.config'),
}),
],
})
export class AppModule {}
创建翻译文件
根据你在配置文件中设置的路径模式,你需要创建相应的翻译文件。例如,如果你的路径模式是 ./src/i18n/__lng__/__ns__.json
,那么你应该创建如下文件结构:
src/
└── i18n/
├── en/
│ └── common.json
└── zh/
└── common.json
每个 .json
文件的内容应该是一个 JSON 对象,包含键值对。例如:
// src/i18n/en/common.json
{
"hello": "Hello",
"welcome": "Welcome to our app!"
}
// src/i18n/zh/common.json
{
"hello": "你好",
"welcome": "欢迎来到我们的应用!"
}
使用
现在你可以在控制器或服务中注入 I18nService
来使用国际化功能:
import { Controller, Get } from '@nestjs/common';
import { I18nService } from '@golevelup/nestjs-i18n';
@Controller('example')
export class ExampleController {
constructor(private readonly i18n: I18nService) {}
@Get()
getExample() {
const hello = this.i18n.translate('common.hello');
return { message: hello };
}
}
这样,当你访问 /example
路由时,它会返回当前语言环境下的 "hello"
翻译。
设置语言
你还可以通过请求头或其他方式动态设置当前的语言环境。例如,在拦截器中设置:
import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { I18nService } from '@golevelup/nestjs-i18n';
@Injectable()
export class LanguageInterceptor implements NestInterceptor {
constructor(private readonly i18n: I18nService) {}
intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
const req = context.switchToHttp().getRequest();
const lang = req.headers['x-lang'] || 'en'; // 从请求头获取语言
this.i18n.setLocale(lang);
return next.handle();
}
}
然后在模块中注册这个拦截器:
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { LanguageInterceptor } from './language.interceptor';
@Module({
providers: [
{
provide: APP_INTERCEPTOR,
useClass: LanguageInterceptor,
},
],
})
export class AppModule {}
这样,你可以通过设置 x-lang
请求头来改变当前的语言环境。
当然,NestJS 的 nestjs-i18n
插件是个好选择!想象一下,你正在为你的应用添加语言功能,就像给你的APP穿上不同国家的传统服饰一样。
首先,你需要安装它:
npm install nestjs-i18n i18n
然后,在你的模块中配置它:
import { Module } from '@nestjs/common';
import { I18nModule } from 'nestjs-i18n';
@Module({
imports: [
I18nModule.forRoot({
fallbackLanguage: 'en',
path: join(__dirname, '/i18n/'),
}),
],
})
export class AppModule {}
接着,在控制器中使用它:
import { Controller, Get, Req, Res } from '@nestjs/common';
import { Request, Response } from 'express';
import { I18n } from 'nestjs-i18n';
@Controller()
export class AppController {
@Get('greet')
greet(@I18n() i18n: any, @Req() req: Request, @Res() res: Response) {
const message = i18n.t('hello');
res.send(message);
}
}
别忘了创建你的翻译文件,比如 en.json
和 zh.json
。现在,你可以切换语言,就像换衣服一样简单!
希望这能帮到你,如果还有问题,欢迎再来问!
nestjs-i18n
是一个用于 NestJS 的国际化(i18n)插件,它基于 i18n
和 i18n-ts
库,提供了对多种语言的支持。下面是如何在你的 NestJS 项目中使用 nestjs-i18n
的步骤和示例。
安装
首先,你需要安装 nestjs-i18n
和相关的依赖:
npm install @nestjs-i18n/core @nestjs-i18n/i18n @nestjs-i18n/translator @nestjs-i18n/loader
然后,根据需要安装具体的语言包,例如:
npm install i18n-abp@zh-Hans-CN
配置
接下来,配置 nestjs-i18n
插件。你可以在 app.module.ts
中进行如下配置:
import { Module } from '@nestjs/common';
import { APP_INTERCEPTOR } from '@nestjs/core';
import { I18nJsonParser, I18nModule } from '@nestjs-i18n';
@Module({
imports: [
I18nModule.forRoot({
parser: I18nJsonParser,
parserOptions: {
path: path.join(__dirname, '/i18n/'),
},
globalPipeOptions: {
exceptionFactory: (err) => new BadRequestException(err),
},
locales: ['en', 'zh'],
defaultLocale: 'en',
}),
],
providers: [
{
provide: APP_INTERCEPTOR,
useClass: I18nInterceptor,
},
],
})
export class AppModule {}
创建翻译文件
在 i18n
目录下创建语言文件,例如 en.json
和 zh.json
:
en.json
{
"greeting": "Hello",
"farewell": "Goodbye"
}
zh.json
{
"greeting": "你好",
"farewell": "再见"
}
使用翻译
在你的服务或控制器中,你可以通过注入 I18nService
来使用翻译:
import { Controller, Get } from '@nestjs/common';
import { I18nService } from '@nestjs-i18n';
@Controller('example')
export class ExampleController {
constructor(private readonly i18n: I18nService) {}
@Get('greet')
greet(@I18n() i18n: I18nService) {
return i18n.translate('greeting');
}
@Get('farewell')
farewell(@I18n() i18n: I18nService) {
return i18n.translate('farewell');
}
}
这样,你就可以根据客户端请求的语言环境自动选择合适的翻译内容了。
结论
以上就是如何在 NestJS 项目中使用 nestjs-i18n
插件的基本步骤。通过这种方式,你可以轻松地为你的应用添加多语言支持,提升用户体验。
NestJS 的 nestjs-i18n
插件可以帮助你实现多语言支持。首先安装插件:
npm install @golevelup/nestjs-i18n i18n
然后,在你的模块中导入 I18nModule
并配置语言文件路径:
import { I18nModule } from '@golevelup/nestjs-i18n';
@Module({
imports: [
I18nModule.forRoot({
fallbackLanguage: 'en',
loaderOptions: {
path: join(__dirname, '/i18n/'),
watch: true,
},
}),
],
})
export class AppModule {}
接着,在服务或控制器中注入 I18nService
来获取对应语言的文本:
constructor(private readonly i18n: I18nService) {}
async someMethod() {
const message = await this.i18n.translate('key', { lang: 'zh-cn' });
}
这样你就可以根据用户的语言设置来显示相应的翻译内容了。