You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于URL路径实现NestJS多语言切换的方案咨询

NestJS 基于URL路径的多语言切换实现步骤

1. 安装依赖

首先安装NestJS官方的i18n工具包:

npm install @nestjs/i18n i18n

2. 配置I18n模块

在AppModule中导入并配置I18nModule,指定路径解析规则、翻译文件位置和默认 fallback 语言:

import { Module } from '@nestjs/common';
import { I18nModule, I18nJsonLoader, PathResolver } from '@nestjs/i18n';
import { join } from 'path';

@Module({
  imports: [
    I18nModule.forRoot({
      fallbackLanguage: 'en',
      loader: I18nJsonLoader,
      loaderOptions: {
        path: join(__dirname, '/i18n/'),
        watch: true, // 开发环境下自动监听翻译文件变更
      },
      resolvers: [
        new PathResolver(['en', 'zh-CN', 'ja']), // 声明支持的语言列表
      ],
    }),
  ],
})
export class AppModule {}

3. 创建翻译文件

在项目src目录下新建i18n文件夹,添加对应语言的JSON翻译文件:

  • src/i18n/en.json
{
  "welcome": "Welcome to our website!",
  "greeting": "Hello, {{name}}!"
}
  • src/i18n/zh-CN.json
{
  "welcome": "欢迎访问我们的网站!",
  "greeting": "你好,{{name}}!"
}
  • src/i18n/ja.json
{
  "welcome": "私たちのウェブサイトへようこそ!",
  "greeting": "こんにちは、{{name}}!"
}

4. 控制器中实现翻译逻辑

在控制器中注入I18nService,结合@I18n()装饰器获取当前语言上下文,实现多语言响应:

import { Controller, Get, Param } from '@nestjs/common';
import { I18nService, I18n } from '@nestjs/i18n';
import { I18nContext } from 'i18n';

@Controller()
export class AppController {
  constructor(private readonly i18n: I18nService) {}

  @Get()
  getWelcome(@I18n() i18nContext: I18nContext) {
    return this.i18n.translate('welcome', {
      lang: i18nContext.lang,
    });
  }

  @Get('greet/:name')
  getGreeting(@Param('name') name: string, @I18n() i18nContext: I18nContext) {
    return this.i18n.translate('greeting', {
      lang: i18nContext.lang,
      args: { name },
    });
  }
}

5. 验证功能

启动项目后,访问不同路径测试效果:

  • 访问 http://localhost:3000/en → 返回 "Welcome to our website!"
  • 访问 http://localhost:3000/zh-CN → 返回 "欢迎访问我们的网站!"
  • 访问 http://localhost:3000/ja/greet/Taro → 返回 "こんにちは、Taro!"

若访问未带语言前缀的路径(如http://localhost:3000),会自动使用配置的fallback语言(此处为en)返回对应内容。

内容的提问来源于stack exchange,提问作者Rian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 22:30:28