Penulis:
    Dibuat:2025-08-23Terakhir diperbarui:2025-08-23

    Terjemahan

    Mendefinisikan Terjemahan

    Fungsi t dalam intlayer memungkinkan Anda untuk mendeklarasikan konten dalam berbagai bahasa. Fungsi ini memastikan keamanan tipe, memberikan error jika ada terjemahan yang hilang, yang sangat berguna dalam lingkungan TypeScript.

    Berikut adalah contoh cara mendeklarasikan konten dengan terjemahan.

    **/*.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>;

    Konfigurasi untuk Lokal

    Untuk memastikan penanganan terjemahan yang tepat, Anda dapat mengonfigurasi lokal yang diterima di intlayer.config.ts. Konfigurasi ini memungkinkan Anda untuk menentukan bahasa yang didukung oleh aplikasi Anda:

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

    Menggunakan Terjemahan dalam Komponen React

    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.

    Objek Konten Kustom

    intlayer mendukung objek konten kustom untuk terjemahan, memungkinkan Anda mendefinisikan struktur yang lebih kompleks sekaligus memastikan keamanan tipe. Berikut adalah contoh dengan objek kustom:

    **/*.content.ts
    import { t, type Dictionary } from "intlayer";
    
    interface ICustomContent {
      title: string;
      content: string;
    }
    
    const customContent = {
      key: "custom_content",
      content: {
        profileText: t<ICustomContent>({
          en: {
            title: "Page Title",
            content: "Page Content",
          },
          fr: {
            title: "Titre de la Page",
            content: "Contenu de la Page",
          },
          es: {
            title: "Título de la Página",
            content: "Contenido de la Página",
          },
        }),
      },
    } satisfies Dictionary;
    
    export default customContent;