首页
/ 使用Intlayer和Express实现后端国际化(i18n)的完整指南

使用Intlayer和Express实现后端国际化(i18n)的完整指南

2025-06-12 13:24:30作者:尤峻淳Whitney

前言:为什么后端也需要国际化?

在全球化应用开发中,前端国际化已经广为人知,但后端国际化同样重要。Intlayer项目提供了一套完整的解决方案,特别是express-intlayer中间件,让Express应用能够轻松实现后端国际化。本文将详细介绍如何利用Intlayer为Express应用添加多语言支持。

核心概念解析

后端国际化的核心价值

  1. 统一用户体验:从API错误信息到邮件通知,保持全栈语言一致性
  2. 动态内容支持:数据库中的多语言内容可以通过API按需返回
  3. 微服务兼容性:在微服务架构中确保各服务返回统一语言格式

Intlayer的核心功能

  • 基于请求自动识别用户语言偏好
  • 类型安全的翻译管理系统
  • 与前端框架无缝集成的能力
  • 灵活的配置选项

实战教程

第一步:环境准备

安装必要的依赖包:

# 使用npm
npm install intlayer express-intlayer

# 使用yarn
yarn add intlayer express-intlayer

# 使用pnpm
pnpm add intlayer express-intlayer

第二步:基础配置

创建intlayer.config.ts配置文件:

import { Locales, type IntlayerConfig } from "intlayer";

const config: IntlayerConfig = {
  internationalization: {
    locales: [
      Locales.ENGLISH,
      Locales.FRENCH,
      Locales.SPANISH_MEXICO,
      Locales.SPANISH_SPAIN,
    ],
    defaultLocale: Locales.ENGLISH,
  },
  middleware: {
    headerName: "accept-language", // 默认使用标准HTTP头
    cookieName: "user_lang",      // 可选cookie支持
  },
};

export default config;

第三步:创建翻译内容

推荐使用TypeScript定义翻译内容以获得最佳类型支持:

// src/messages.content.ts
import { t, type Dictionary } from "intlayer";

export const messages = {
  key: "user_messages",
  content: {
    welcome: t({
      en: "Welcome to our service",
      fr: "Bienvenue sur notre service",
      "es-ES": "Bienvenido a nuestro servicio",
      "es-MX": "Bienvenido a nuestro servicio",
    }),
    error: {
      notFound: t({
        en: "Resource not found",
        fr: "Ressource introuvable",
        "es-ES": "Recurso no encontrado",
        "es-MX": "Recurso no encontrado",
      }),
    },
  },
} satisfies Dictionary;

第四步:集成到Express应用

完整集成示例:

import express from "express";
import { intlayer, t, getDictionary, getIntlayer } from "express-intlayer";
import { messages } from "./messages.content";

const app = express();

// 启用国际化中间件
app.use(intlayer());

// 示例路由
app.get("/api/welcome", (req, res) => {
  // 方法1:直接使用t函数
  res.json({
    message: t({
      en: "Hello World",
      fr: "Bonjour le monde",
      "es-ES": "Hola Mundo",
      "es-MX": "Hola Mundo",
    }),
  });
});

app.get("/api/messages", (req, res) => {
  // 方法2:从内容声明中获取
  res.json(getDictionary(messages));
});

app.get("/api/errors/404", (req, res) => {
  // 方法3:通过key获取
  res.status(404).json({
    error: getIntlayer("user_messages").error.notFound,
  });
});

app.listen(3000, () => console.log("Server running on port 3000"));

高级用法

自定义语言检测逻辑

// 自定义中间件示例
app.use((req, res, next) => {
  // 从自定义header获取语言
  const customLang = req.headers["x-custom-lang"];
  if (customLang) {
    req.locale = customLang.toString();
  }
  next();
});

// 然后应用intlayer中间件
app.use(intlayer());

动态内容国际化

app.get("/api/products/:id", async (req, res) => {
  const product = await Product.findById(req.params.id);
  
  res.json({
    ...product,
    // 将产品描述国际化
    description: t({
      en: product.description_en,
      fr: product.description_fr,
      "es-ES": product.description_es,
    }),
  });
});

开发工具推荐

TypeScript配置

确保tsconfig.json包含:

{
  "compilerOptions": {
    "strict": true,
    "types": ["intlayer/types"]
  },
  "include": [
    "src/**/*",
    ".intlayer/**/*.ts"
  ]
}

VS Code扩展

Intlayer官方扩展提供:

  • 实时翻译预览
  • 缺失翻译警告
  • 快速跳转到定义
  • 自动补全支持

最佳实践

  1. 目录结构:按功能模块组织翻译文件

    /src
      /i18n
        /auth
          login.content.ts
          register.content.ts
        /products
          listing.content.ts
          details.content.ts
    
  2. 错误处理:统一错误消息格式

    // errors.content.ts
    export const errors = {
      key: "errors",
      content: {
        validation: {
          email: t({...}),
          password: t({...}),
        },
        server: {
          internal: t({...}),
        },
      },
    };
    
  3. 性能优化

    • 对频繁访问的翻译内容进行缓存
    • 考虑使用CDN分发静态翻译内容
    • 实现按需加载翻译包

常见问题解答

Q:如何处理动态插值的翻译? A:Intlayer支持参数化翻译:

const messages = {
  greeting: t({
    en: "Hello, {name}!",
    fr: "Bonjour, {name}!",
  }),
};

// 使用时
const greeting = t(messages.greeting, { name: "Alice" });

Q:如何测试不同语言? A:可以通过以下方式测试:

  1. 修改浏览器语言偏好
  2. 使用Postman设置Accept-Language
  3. 添加?lang=es查询参数(需额外配置)

Q:翻译内容如何与团队协作? A:建议:

  1. .content文件纳入版本控制
  2. 建立翻译键名命名规范
  3. 使用提取工具生成待翻译文件

总结

通过Intlayer和Express的集成,开发者可以轻松构建支持多语言的后端服务。关键优势包括:

  1. 类型安全的翻译管理系统
  2. 灵活的部署选项
  3. 与前端框架的无缝集成
  4. 完善的开发者工具支持

无论是构建全栈国际化应用,还是仅为API添加多语言支持,Intlayer都提供了优雅的解决方案。

登录后查看全文
热门项目推荐

项目优选

收起
ohos_react_nativeohos_react_native
React Native鸿蒙化仓库
C++
176
261
RuoYi-Vue3RuoYi-Vue3
🎉 (RuoYi)官方仓库 基于SpringBoot,Spring Security,JWT,Vue3 & Vite、Element Plus 的前后端分离权限管理系统
Vue
860
511
ShopXO开源商城ShopXO开源商城
🔥🔥🔥ShopXO企业级免费开源商城系统,可视化DIY拖拽装修、包含PC、H5、多端小程序(微信+支付宝+百度+头条&抖音+QQ+快手)、APP、多仓库、多商户、多门店、IM客服、进销存,遵循MIT开源协议发布、基于ThinkPHP8框架研发
JavaScript
93
15
openGauss-serveropenGauss-server
openGauss kernel ~ openGauss is an open source relational database management system
C++
129
182
openHiTLSopenHiTLS
旨在打造算法先进、性能卓越、高效敏捷、安全可靠的密码套件,通过轻量级、可剪裁的软件技术架构满足各行业不同场景的多样化要求,让密码技术应用更简单,同时探索后量子等先进算法创新实践,构建密码前沿技术底座!
C
259
300
kernelkernel
deepin linux kernel
C
22
5
cherry-studiocherry-studio
🍒 Cherry Studio 是一款支持多个 LLM 提供商的桌面客户端
TypeScript
596
57
CangjieCommunityCangjieCommunity
为仓颉编程语言开发者打造活跃、开放、高质量的社区环境
Markdown
1.07 K
0
HarmonyOS-ExamplesHarmonyOS-Examples
本仓将收集和展示仓颉鸿蒙应用示例代码,欢迎大家投稿,在仓颉鸿蒙社区展现你的妙趣设计!
Cangjie
398
371
Cangjie-ExamplesCangjie-Examples
本仓将收集和展示高质量的仓颉示例代码,欢迎大家投稿,让全世界看到您的妙趣设计,也让更多人通过您的编码理解和喜爱仓颉语言。
Cangjie
332
1.08 K