作者:
    Creation:2024-08-11Last update:2025-06-29

    翻译

    定义翻译

    intlayer 中的 t 函数允许您声明多语言内容。该函数确保类型安全,如果缺少任何翻译会抛出错误,这在 TypeScript 环境中特别有用。

    以下是如何声明带有翻译内容的示例。

    **/*.content.ts
    import { t, type Dictionary } from "intlayer";
    
    interface Content {
      welcomeMessage: string;
    }
    
    export default {
      key: "multi_lang",
      content: {
        welcomeMessage: t({
          en: "Welcome to our application",
          fr: "Bienvenue dans notre application",
          es: "Bienvenido a nuestra aplicación",
        }),
      },
    } satisfies Dictionary<Content>;

    本地化配置

    为了确保正确处理翻译,您可以在 intlayer.config.ts 中配置接受的本地化语言。此配置允许您定义应用程序支持的语言:

    intlayer.config.ts
    import { Locales, type IntlayerConfig } from "intlayer";
    
    const config: IntlayerConfig = {
      internationalization: {
        locales: [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH],
      },
    };
    
    export default config;

    本地化配置

    With react-intlayer, you can use translations in React components. Here's an example:

    **/*.tsx
    import type { FC } from "react";
    import { useIntlayer } from "react-intlayer";
    
    const MyComponent: FC = () => {
    const content = useIntlayer("multi_lang");
    
    return (
      <div>
        <p>{content.welcomeMessage}</p>
      </div>
    );
    };
    
    export default MyComponent;

    This component fetches the corresponding translation based on the current locale set in your application.