面试题答案
一键面试常用库
- i18next:功能丰富,支持多种特性,如复数、嵌套翻译等,社区活跃,文档完善。
- node-i18n:相对轻量级,易于上手,提供基本的国际化功能。
- lingui:专注于React应用的国际化,但也可用于Node.js项目,提供编译时优化等特性。
使用 i18next 进行简单文本翻译
- 安装:
在项目目录下运行
npm install i18next
安装库。 - 初始化:
在代码中引入并初始化
i18next
。例如:
const i18next = require('i18next');
const resources = {
en: {
translation: {
greeting: 'Hello'
}
},
de: {
translation: {
greeting: 'Hallo'
}
}
};
i18next.init({
resources,
lng: 'en', // 默认语言
interpolation: {
escapeValue: false // 不转义HTML标签
}
});
- 翻译文本:
使用
t
方法进行翻译。例如:
i18next.t('greeting').then((translation) => {
console.log(translation); // 输出 'Hello'
});
- 加载外部翻译文件:
可使用
i18next - fs - backend
来加载外部JSON文件作为翻译资源。- 安装:
npm install i18next - fs - backend
- 配置:
- 安装:
const i18next = require('i18next');
const Backend = require('i18next - fs - backend');
i18next
.use(Backend)
.init({
backend: {
loadPath: __dirname + '/locales/{{lng}}/{{ns}}.json'
},
lng: 'en',
ns: 'translation',
defaultNS: 'translation'
});
假设在 locales/en/translation.json
文件中有 {"greeting": "Hello"}
,在 locales/de/translation.json
文件中有 {"greeting": "Hallo"}
,就可按上述配置加载并使用不同语言的翻译。