You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

astro-i18next中t()函数显示键而非翻译内容的问题求助

Astro i18next 翻译失效问题

使用t()函数做文本翻译时,函数完全不读取/public下的语言包,直接输出传入的键名而非翻译内容。执行npx astro-i18next generate命令也没有任何效果。

文件结构

文件结构

英文语言包内容(/public/locales/en/translation.json)

{
    "index": {
        "testHeader": "Test Header"
    }
}

首页代码(src/pages/index.astro)

---
import Layout from "../layouts/Layout.astro";
import { t, changeLanguage } from "i18next";

changeLanguage("en");
---

<Layout>
    <h1>{t("index.testHeader")}</h1>
</Layout>

astro-i18next.config.mts 配置

/** @type {import('astro-i18next').AstroI18nextConfig} */
export default {
    defaultLocale: "en",
    locales: ["en", "cs"],
};

astro.config.mjs 配置

import { defineConfig } from 'astro/config';
import astroI18next from "astro-i18next";
import tailwind from '@astrojs/tailwind';
import react from "@astrojs/react";

export default defineConfig({
    integrations: [astroI18next(), react(), tailwind({
        config: './tailwind.config.cjs',
    })]
});

问题表现

t()函数直接显示键名


解决方法

  • 检查语言包路径:确保语言包严格放在public/locales/{locale}/translation.json路径下,比如英文包必须是public/locales/en/translation.json,路径层级和文件名不能出错。
  • 调整changeLanguage调用位置:Astro组件脚本区(---内)是服务端执行逻辑,直接调用changeLanguage可能无法正确初始化i18next。建议移到客户端<script>标签中执行:
    ---
    import Layout from "../layouts/Layout.astro";
    import { t } from "i18next";
    ---
    
    <Layout>
        <h1>{t("index.testHeader")}</h1>
    </Layout>
    
    <script>
        import { changeLanguage } from "i18next";
        changeLanguage("en");
    </script>
    
  • 手动初始化i18next:若上述方法无效,在src/i18n.ts中手动配置初始化逻辑:
    import i18next from "i18next";
    import { initReactI18next } from "react-i18next";
    import Backend from "i18next-http-backend";
    import LanguageDetector from "i18next-browser-languagedetector";
    
    i18next
      .use(Backend)
      .use(LanguageDetector)
      .use(initReactI18next)
      .init({
        fallbackLng: "en",
        debug: false,
        interpolation: {
          escapeValue: false,
        },
      });
    
    export default i18next;
    
    之后在布局组件中导入该文件即可。
  • 更新依赖并重启服务:执行npm update astro-i18next更新依赖,修改配置或语言包后必须重启Astro开发服务,否则修改不生效。

内容的提问来源于stack exchange,提问作者Mihal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 04:15:38