在Express中使用i18next

发布时间 2023-08-11 16:07:30作者: ChrisLeon

背景

框架:Express
语法:TypeScript
配置插件:i18next

安装

npm install i18next --save
npm install i18next-http-middleware --save

项目配置

装饰器

src根目录创建装饰器i18next.d.ts

import "i18next";
import enLocales from "./locales/en";
import zhLocales from "./locales/zh-CN";

declare module "i18next" {

  // Extend CustomTypeOptions

  interface CustomTypeOptions {
    locales: ['en', 'zh'],
    queryParameter: 'lang', // 设置查询参数
    defaultLocale: 'en',
    resources: {
        zh: typeof zhLocales,
        en: typeof enLocales

    }    

  }

}

语言文件

创建json配置与公共输出口:
(举例zh,其他语言也一样)
路径: locales/en/index.ts

import * as user from "./user.json"
const zhLocales = {
    user
}
export default zhLocales

路径:locales/en/user.json

{
    "HTTP_CODE_403":"服务器理解该请求,但不会满足它"
}

注册配置

在根目录的server.ts 内添加

import i18next from "i18next";
import * as i18nextMiddleware from 'i18next-http-middleware'

const app = express();

//其他配置

// ========= LOCALIZATION
i18next.use(i18nextMiddleware.LanguageDetector).init({
    preload: ['en', 'zh']
})

app.use(i18nextMiddleware.handle(i18next,{
    removeLngFromUrl:false
}));

//注册路由

使用

在路由中使用:

router.post("/", async(req: Request, res: Response) => {
	const { email } = req.body;
	if (user) {
		res.status(HttpStatusCodes.FORBIDDEN).json(
			{
				msg:  t("zh:user.HTTPODE_403")
			}
         )
     }
})

官方文档:
https://www.i18next.com/overview/typescript