用途:为 Shopify 应用添加多语言支持。资料指出 Shopify 商家遍布全球,应用需支持多语言才更易被采用。
技术栈:使用 i18next 作为标准库,React 侧用 react-i18next,Remix 侧用 remix-i18next。
安装:npm install i18next react-i18next remix-i18next i18next-fs-backend i18next-http-backend
服务端配置:在 app/i18n.server.ts 创建服务端实例用于检测语言,使用 RemixI18Next 并设置 supportedLanguages、fallbackLanguage,i18next 后端 loadPath 指向 ./public/locales/{{lng}}/{{ns}}.json。
根路由:在 app/root.tsx 的 loader 中用 i18nServer.getLocale(request) 获取 locale 并返回;通过 handle 导出 i18n 命名空间(如 "common")加载对应路由翻译;组件内使用 useChangeLanguage(locale) 同步,并在 html 标签上设置 lang 与 dir。
翻译文件:存放于 public/locales,按语言与命名空间组织,例如 en/common.json、fr/common.json、vi/common.json,支持嵌套键值。
组件用法:通过 useTranslation("common") 取得 t 函数,如 t("dashboard.title")、t("welcome")。
Admin 语言检测:Shopify 会在 URL 查询参数中传入 locale(如 ?locale=fr-FR),也可从 GraphQL Admin API 获取;配置正确时 remix-i18next 的检测可自动处理请求头或查询参数。
扩展翻译:Theme App Extensions 与 Checkout UI Extensions 各自拥有独立 locales 目录,不共享 Remix 应用的翻译文件,例如 extensions/my-ext/locales/en.default.json 与 extensions/checkout-ui/locales/en.json。
限制:资料未提供具体版本要求、支持语言清单、性能或缓存策略等细节,暂未提供。