面试题答案
一键面试- 安装:
- 在Svelte项目根目录下,通过npm或yarn安装
i18next
和svelte - i18next
。
npm install i18next svelte - i18next # 或者 yarn add i18next svelte - i18next
- 在Svelte项目根目录下,通过npm或yarn安装
- 初始化:
- 在项目的入口文件(例如
main.js
)中,导入并初始化i18next
。
import i18n from 'i18next'; import { initReactI18next } from'react - i18next'; import Backend from 'i18next - http - backend'; import LanguageDetector from 'i18next - browser - language - detector'; i18n .use(Backend) .use(LanguageDetector) .use(initReactI18next) .init({ fallbackLng: 'en', interpolation: { escapeValue: false } });
- 这里使用了
i18next - http - backend
来从后端加载翻译文件,i18next - browser - language - detector
来自动检测用户浏览器的语言设置,initReactI18next
是i18next
与React集成的插件(虽然是Svelte项目,但svelte - i18next
基于此)。fallbackLng
设置了默认语言为英语。
- 在项目的入口文件(例如
- 在Svelte组件中引入使用:
- 首先导入
useTranslation
函数。
<script> import { useTranslation } from'svelte - i18next'; const { t } = useTranslation(); </script> <p>{t('welcome')}</p>
- 这里通过
useTranslation
函数获取t
函数,t
函数用于根据当前语言环境翻译键值。假设在翻译文件中有welcome
这个键对应不同语言的“欢迎”表述,就可以通过{t('welcome')}
在组件中展示相应语言的文本。同时,需要确保翻译文件(例如en.json
,zh - CN.json
等)中包含welcome
键及其对应的值,如下是en.json
示例:
{ "welcome": "Welcome" }
- 以及
zh - CN.json
示例:
{ "welcome": "欢迎" }
- 首先导入