Ana SayfaPlaygroundShowcaseUygulamaDokümanBlog
    • Englishİngilizce
      EN
    • русскийRusça
      RU
    • 日本語Japonca
      JA
    • françaisFransızca
      FR
    • 한국어Korece
      KO
    • 中文Çince
      ZH
    • españolİspanyolca
      ES
    • DeutschAlmanca
      DE
    • العربيةArapça
      AR
    • italianoİtalyanca
      IT
    • British Englishİngiliz İngilizcesi
      EN-GB
    • portuguêsPortekizce
      PT
    • हिन्दीHintçe
      HI
    • TürkçeTürkçe
      TR
    • polskiLehçe
      PL
    • IndonesiaEndonezce
      ID
    • Tiếng ViệtVietnamca
      VI
    • українськаUkraynaca
      UK
    /
    Çerçeveye göre belgeleri filtrele
    Alt+←
    Neden Intlayer?
    Başla
    Kavram
    • Intlayer Nasıl Çalışır
    • Yapılandırma
    • TestFillBuildWatchExtractLoginPushPullConfigurationListVersionEditorLiveDebugDoc ReviewDoc TranslateSDK
    • Görsel Editör
    • CMS
    • CI/CD Entegrasyonu
    • ÇeviriÇoğulNumaralandırmaKoşulCinsiyetEklemeDosyaİç İçe GeçmeMarkdownHTMLFonksiyon Getirme
    • Yerel Dosya
    • Derleyici
    • Otomatik Doldurma
    • Test
    • Paket Optimizasyonu
    Ortam
    • Next.js 14 ve Uygulama Yönlendirici
      Next.js 15
      Next.js locale’siz URL
      Next.js ve Sayfa Yönlendirici
      Derleyici
    • Tanstack Start Solid
    • Astro ve React
      Astro ve Svelte
      Astro ve Vue
      Astro ve Solid
      Astro ve Preact
      Astro ve Lit
      Astro ve Vanilla JS
    • React Router v7
      React Router v7 (fs-routes)
      Compiler
    • Nuxt ve Vue
    • Vite ve Solid
    • SvelteKit
    • Vite ve Preact
    • Vite ve Vanilla JS
    • Vite ve Lit
    • Angular 19 (Webpack)
      Analog
    • React CRA
    • React Native ve Expo
    • Express.js
      NestJS
      Fastify
      Hono
      Adonis
    • Lynx ve React
    Plugins
    • JSON
    • gettext (.po)
    VS Code Uzantısı
    Aracı
    • MCP Sunucusu
    • Aracı becerileri
    Sürümler
    • v8
    • v7
    • v6
    Karşılaştırma
    • Next.js
    • TanStack
    • Vue
    • Solid
    • Svelte
    Blog
    Bir soru sor
    1. Documentation
    2. Ortam
    3. Tanstack Start
    Oluşturma:2025-09-09Son güncelleme:2026-05-06
    GitHub'da uygulama şablonunu görüntüle

    Bu sayfada kullanılabilir bir uygulama şablonu var.

    Vitrin uygulamasını görüntüle

    Bu sayfa şablonun canlı demosuna bağlanır.

    Video eğitimini izleyin

    Bu sayfada bir video eğitimi mevcuttur.

    Bu dokümanı favori AI asistanınıza referans verin
    ChatGPT
    Claude
    DeepSeek
    Google AI mode
    Gemini
    Perplexity
    Mistral
    Grok

    Sorunuzu sorun ve bu sayfaya ve seçtiğiniz AI sağlayıcısına referans vererek belgenin bir özetini alın

    Sürüm Geçmişi

    1. "Solid useIntlayer API kullanımını doğrudan özellik erişimine güncelle"
      v8.9.004.05.2026
    2. "init komutu ekle"
      v7.5.930.12.2025
    3. "validatePrefix'i tanıt ve 14. adımı ekle: Yerelleştirilmiş rotalarla 404 sayfalarını ele alma."
      v7.4.011.12.2025
    4. "13. adımı ekle: Sunucu işlemlerinde locale bilgisini almak (Opsiyonel)"
      v7.3.905.12.2025
    5. "13. adımı ekle: Nitro'yu uyarla"
      v7.2.318.11.2025
    6. "getPrefix fonksiyonunu ekleyerek useLocalizedNavigate, LocaleSwitcher ve LocalizedLink için önek varsayılanını düzelt."
      v7.1.017.11.2025
    7. "Doküman güncellemesi"
      v6.5.203.10.2025
    8. "Tanstack Start için eklendi"
      v5.8.109.09.2025

    Bu sayfanın içeriği bir yapay zeka kullanılarak çevrildi.

    Orijinal içeriğin İngilizce son sürümünü görüntüleyin
    Bu dokümanı düzenle

    Bu dokümantasyonu geliştirmek için bir fikriniz varsa, lütfen GitHub'da bir çekme isteği göndererek katkıda bulunmaktan çekinmeyin.

    Dokümantasyon için GitHub bağlantısı
    Kopyala

    Belge Markdown'ını panoya kopyala

    Intlayer ile Tanstack Start sitenizi çevirin | Uluslararasılaştırma (i18n)

    İçindekiler

    Bu rehber, Tanstack Start projelerinde yerel dil yönlendirmesi, TypeScript desteği ve modern geliştirme uygulamalarıyla sorunsuz uluslararasılaştırma için Intlayer'ın nasıl entegre edileceğini göstermektedir.

    Intlayer Nedir?

    Intlayer, modern web uygulamalarında çok dilli desteği basitleştirmek için tasarlanmış yenilikçi, açık kaynaklı bir uluslararasılaştırma (i18n) kütüphanesidir.

    Intlayer ile şunları yapabilirsiniz:

    • Bileşen seviyesinde bildirisel sözlükler kullanarak çevirileri kolayca yönetin.
    • Meta verileri, yönlendirmeleri ve içeriği dinamik olarak yerelleştirin.
    • Otomatik oluşturulan tiplerle TypeScript desteğini sağlayarak otomatik tamamlama ve hata tespitini geliştirin.
    • Dinamik yerel dil algılama ve değiştirme gibi gelişmiş özelliklerden faydalanın.
    • Tanstack Start'ın dosya tabanlı yönlendirme sistemi ile yerel dil farkındalıklı yönlendirmeyi etkinleştirin.

    Tanstack Start Uygulamasında Intlayer Kurulumu için Adım Adım Rehber

    www.youtube.com
    ide.intlayer.org
    intlayer-tanstack-start-template.vercel.app

    GitHub'da Uygulama Şablonu sayfasına bakın.

    Adım 1: Proje Oluşturma

    TanStack Start web sitesindeki Yeni proje başlatma rehberini takip ederek yeni bir TanStack Start projesi oluşturun.

    Adım 2: Intlayer Paketlerini Yükleyin

    Tercih ettiğiniz paket yöneticisini kullanarak gerekli paketleri yükleyin:

    bash
    Kodu kopyala

    Kodu panoya kopyala

    npm install intlayer react-intlayernpm install vite-intlayer --save-devnpx intlayer init
    • intlayer

      Yapılandırma yönetimi, çeviri, içerik bildirimi, dönüştürme ve CLI komutları için uluslararasılaştırma araçları sağlayan temel paket.

    • react-intlayer Intlayer'ı React uygulamasıyla entegre eden paket. React uluslararasılaştırması için bağlam sağlayıcıları ve kancalar sunar.

    • vite-intlayer Intlayer'ı Vite paketleyicisi ile entegre etmek için Vite eklentisini içerir; ayrıca kullanıcının tercih ettiği yereli algılayan, çerezleri yöneten ve URL yönlendirmesini ele alan ara yazılımı da kapsar.

    Adım 3: Projenizin Yapılandırılması

    Uygulamanızın dillerini yapılandırmak için bir yapılandırma dosyası oluşturun:

    intlayer.config.ts
    Kodu kopyala

    Kodu panoya kopyala

    import type { IntlayerConfig } from "intlayer";import { Locales } from "intlayer";const config: IntlayerConfig = {  internationalization: {    defaultLocale: Locales.ENGLISH,    locales: [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH],  },};export default config;
    Bu yapılandırma dosyası aracılığıyla, yerelleştirilmiş URL'ler, ara yazılım yönlendirmesi, çerez isimleri, içerik bildirimlerinizin konumu ve uzantısı, Intlayer günlüklerini konsolda devre dışı bırakma ve daha fazlasını ayarlayabilirsiniz. Mevcut parametrelerin tam listesi için yapılandırma dokümantasyonuna bakınız.

    Adım 4: Intlayer'ı Vite Yapılandırmanıza Entegre Edin

    Yapılandırmanıza intlayer eklentisini ekleyin:

    vite.config.ts
    Kodu kopyala

    Kodu panoya kopyala

    import { tanstackStart } from "@tanstack/react-start/plugin/vite";import viteReact from "@vitejs/plugin-react";import { nitro } from "nitro/vite";import { defineConfig } from "vite";import { intlayer } from "vite-intlayer";const config = defineConfig({  plugins: [    nitro(),    intlayer(),    tanstackStart({      router: {        routeFileIgnorePattern:          ".content.(ts|tsx|js|mjs|cjs|jsx|json|jsonc|json5)$",      },    }),    viteReact(),  ],});export default config;
    intlayer() Vite eklentisi, Intlayer'ı Vite ile entegre etmek için kullanılır. İçerik bildirim dosyalarının oluşturulmasını sağlar ve geliştirme modunda bunları izler. Vite uygulaması içinde Intlayer ortam değişkenlerini tanımlar. Ayrıca performansı optimize etmek için takma adlar sağlar.

    Adım 5: Kök Düzen (Root Layout) Oluşturma

    Kök düzeninizi uluslararasılaştırmayı destekleyecek şekilde yapılandırın; useParams kullanarak mevcut yerel ayarı tespit edin ve html etiketinde lang ve dir özniteliklerini ayarlayın.

    src/routes/__root.tsx
    Kodu kopyala

    Kodu panoya kopyala

    import {  createRootRouteWithContext,  HeadContent,  Scripts,} from "@tanstack/react-router";import { defaultLocale, getHTMLTextDir } from "intlayer";import { type ReactNode } from "react";import { IntlayerProvider } from "react-intlayer";import { Route as LocaleRoute } from "./{-$locale}/route";export const Route = createRootRouteWithContext<{}>()({  head: () => ({    meta: [      {        charSet: "utf-8",      },      {        content: "width=device-width, initial-scale=1",        name: "viewport",      },      {        title: "TanStack Start Starter",      },    ],  }),  shellComponent: RootDocument,});function RootDocument({ children }: { children: ReactNode }) {  const params = LocaleRoute.useParams();  const locale = params?.locale ?? defaultLocale;  return (    <html dir={getHTMLTextDir(locale)} lang={locale}>      <head>        <HeadContent />      </head>      <body>        <IntlayerProvider locale={locale}>{children}</IntlayerProvider>        <Scripts />      </body>    </html>  );}
    İçeriğinizi bir string niteliğinde kullanmak istiyorsanız, alt, title, href, aria-label vb. gibi, fonksiyonun değerini çağırmanız gerekir:
    html
    Kodu kopyala

    Kodu panoya kopyala

    <img src="{content.image.src.value}" alt="{content.image.value}" /><img src="{content.image.src.toString()}" alt="{content.image.toString()}" /><img src="{String(content.image.src)}" alt="{String(content.image)}" />

    Adım 6: Yerel Dil Düzeni Oluşturma

    Yerel ayar ön ekini işleyen ve doğrulama gerçekleştiren bir düzen oluşturun.

    src/routes/{-$locale}/route.tsx
    Kodu kopyala

    Kodu panoya kopyala

    import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";import { validatePrefix } from "intlayer";export const Route = createFileRoute("/{-$locale}")({  beforeLoad: ({ params }) => {    const localeParam = params.locale;    // Yerel ayar ön ekini doğrula    const { isValid, localePrefix } = validatePrefix(localeParam);    if (!isValid) {      throw redirect({        to: "/{-$locale}/404",        params: { locale: localePrefix },      });    }  },  component: Outlet,});
    Burada {-$locale}, mevcut yerel ayar ile değiştirilen dinamik bir rota parametresidir. Bu gösterim, slotu isteğe bağlı hale getirerek 'prefix-no-default' vb. gibi yönlendirme modlarıyla çalışmasına olanak tanır.

    Aynı rotada birden fazla dinamik segment kullanıyorsanız bu slotun sorunlara yol açabileceğini unutmayın (örneğin, /{-$locale}/other-path/$anotherDynamicPath/...). 'prefix-all' modu için slotu $locale olarak değiştirmeyi tercih edebilirsiniz. 'no-prefix' veya 'search-params' modu için slotu tamamen kaldırabilirsiniz.

    Adım 7: İçeriğinizi Bildirin

    Çevirileri depolamak için içerik bildirimlerinizi oluşturun ve yönetin:

    src/contents/page.content.ts
    Kodu kopyala

    Kodu panoya kopyala

    import type { Dictionary } from "intlayer";import { t } from "intlayer";const appContent = {  content: {    links: {      about: t({        en: "About",        es: "Acerca de",        fr: "À propos",      }),      home: t({        en: "Home",        es: "Inicio",        fr: "Accueil",      }),    },    meta: {      title: t({        en: "Welcome to Intlayer + TanStack Router",        es: "Bienvenido a Intlayer + TanStack Router",        fr: "Bienvenue à Intlayer + TanStack Router",      }),      description: t({        en: "This is an example of using Intlayer with TanStack Router",        es: "Este es un ejemplo de uso de Intlayer con TanStack Router",        fr: "Ceci est un exemple d'utilisation d'Intlayer avec TanStack Router",      }),    },  },  key: "app",} satisfies Dictionary;export default appContent;
    İçerik bildirimleriniz, uygulamanızda herhangi bir yerde tanımlanabilir, yeter ki contentDir dizinine dahil edilsin (varsayılan olarak, ./app). Ve içerik bildirim dosya uzantısıyla eşleşmelidir (varsayılan olarak, .content.{json,ts,tsx,js,jsx,mjs,cjs}).
    Daha fazla ayrıntı için, içerik bildirim dokümantasyonuna bakınız.

    Adım 8: Yerel Dili Algılayan Bileşenler ve Hook'lar Oluşturun

    Yerel dil algılayan gezinme için bir LocalizedLink bileşeni oluşturun:

    src/components/localized-link.tsx
    Kodu kopyala

    Kodu panoya kopyala

    import type { FC } from "react";import { Link, type LinkComponentProps } from "@tanstack/react-router";import { useLocale } from "react-intlayer";import { getPrefix } from "intlayer";export const LOCALE_ROUTE = "{-$locale}" as const;export type To = StripLocalePrefix<LinkComponentProps["to"]>;export type StripLocalePrefix<T extends string | undefined> = T extends  | `/${typeof LOCALE_ROUTE}/`  | `/${typeof LOCALE_ROUTE}`  ? "/"  : T extends `/${typeof LOCALE_ROUTE}/${infer Rest}`    ? `/${Rest}`    : T;type LocalizedLinkProps = {  to?: To;} & Omit<LinkComponentProps, "to">;export const LocalizedLink: FC<LocalizedLinkProps> = (props) => {  const { locale } = useLocale();  const { localePrefix } = getPrefix(locale);  return (    <Link      {...props}      params={{        locale: localePrefix,        ...(typeof props?.params === "object" ? props?.params : {}),      }}      to={`/${LOCALE_ROUTE}${props.to}` as LinkComponentProps["to"]}    />  );};

    Bu bileşenin iki amacı vardır:

    • URL'den gereksiz {-$locale} önekini kaldırmak.
    • Kullanıcının doğrudan yerelleştirilmiş rotaya yönlendirilmesini sağlamak için URL'ye locale parametresini enjekte etmek.

    Daha sonra programatik gezinme için bir useLocalizedNavigate kancası oluşturabiliriz:

    src/hooks/useLocalizedNavigate.tsx
    Kodu kopyala

    Kodu panoya kopyala

    import { useNavigate } from "@tanstack/react-router";import { getPrefix } from "intlayer";import { useLocale } from "react-intlayer";import type { StripLocalePrefix } from "@/components/localized-link";import type { FileRouteTypes } from "@/routeTree.gen";type NavigateFn = ReturnType<typeof useNavigate>;type BaseNavigateOptions = Parameters<NavigateFn>[0];type LocalizedTo = StripLocalePrefix<FileRouteTypes["to"]>;export type LocalizedNavigateOptions = Omit<  BaseNavigateOptions,  "to" | "params"> & {  to: LocalizedTo;  params?: Omit<NonNullable<BaseNavigateOptions["params"]>, "locale">;};type LocalizedNavigate = (  options: LocalizedNavigateOptions) => ReturnType<NavigateFn>;export const useLocalizedNavigate = () => {  const navigate = useNavigate();  const { locale } = useLocale();  const localizedNavigate: LocalizedNavigate = (args: any) => {    const { localePrefix } = getPrefix(locale);    if (typeof args === "string") {      return navigate({        to: `/${LOCALE_ROUTE}${args}`,        params: { locale: localePrefix },      });    }    const { to, ...rest } = args;    const localizedTo = `/${LOCALE_ROUTE}${to}` as any;    return navigate({      to: localizedTo,      params: { locale: localePrefix, ...rest } as any,    });  };  return localizedNavigate;};

    Adım 9: Sayfalarınızda Intlayer'ı Kullanın

    Uygulamanız genelinde içerik sözlüklerinize erişin:

    Yerelleştirilmiş Ana Sayfa

    src/routes/{-$locale}/index.tsx
    Kodu kopyala

    Kodu panoya kopyala

    import { createFileRoute } from "@tanstack/react-router";import { getIntlayer } from "intlayer";import { useIntlayer } from "react-intlayer";import LocaleSwitcher from "@/components/locale-switcher";import { LocalizedLink } from "@/components/localized-link";import { useLocalizedNavigate } from "@/hooks/useLocalizedNavigate";export const Route = createFileRoute("/{-$locale}/")({  component: RouteComponent,});function RouteComponent() {  const content = useIntlayer("app");  const navigate = useLocalizedNavigate();  return (    <div>      <div>        {content.title}        <LocaleSwitcher />        <div>          <LocalizedLink to="/">{content.links.home}</LocalizedLink>          <LocalizedLink to="/about">{content.links.about}</LocalizedLink>        </div>        <div>          <button onClick={() => navigate({ to: "/" })}>            {content.links.home}          </button>          <button onClick={() => navigate({ to: "/about" })}>            {content.links.about}          </button>        </div>      </div>    </div>  );}
    useIntlayer kancasını daha fazla öğrenmek için, belgelere bakınız.

    Adım 10: Bir Dil Değiştirici (Locale Switcher) Bileşeni Oluşturun

    Kullanıcıların dilleri değiştirmesine izin veren bir bileşen oluşturun:

    src/components/locale-switcher.tsx
    Kodu kopyala

    Kodu panoya kopyala

    import { useLocation } from "@tanstack/react-router";import {  getHTMLTextDir,  getLocaleName,  getPathWithoutLocale,  getPrefix,  Locales,} from "intlayer";import type { FC } from "react";import { useLocale } from "react-intlayer";import { LocalizedLink, type To } from "./localized-link";export const LocaleSwitcher: FC = () => {  const { pathname } = useLocation();  const { availableLocales, locale, setLocale } = useLocale();  const pathWithoutLocale = getPathWithoutLocale(pathname);  return (    <ol>      {availableLocales.map((localeEl) => (        <li key={localeEl}>          <LocalizedLink            aria-current={localeEl === locale ? "page" : undefined}            onClick={() => setLocale(localeEl)}            params={{ locale: getPrefix(localeEl).localePrefix }}            to={pathWithoutLocale as To}          >            <span>              {/* Dil Kodu - örn. FR */}              {localeEl}            </span>            <span>              {/* Dil kendi yerelinde - örn. Français */}              {getLocaleName(localeEl, locale)}            </span>            <span dir={getHTMLTextDir(localeEl)} lang={localeEl}>              {/* Dil mevcut yerelde - örn. Francés, mevcut yerel Locales.SPANISH olarak ayarlanmış */}              {getLocaleName(localeEl)}            </span>            <span dir="ltr" lang={Locales.ENGLISH}>              {/* Dil İngilizce olarak - örn. French */}              {getLocaleName(localeEl, Locales.ENGLISH)}            </span>          </LocalizedLink>        </li>      ))}    </ol>  );};
    useLocale hook'u hakkında daha fazla bilgi edinmek için belgelere bakınız.

    Adım 11: HTML Öznitelik Yönetimi

    Adım 5'te görüldüğü gibi, kök bileşeninizde useParams kullanarak html etiketinin lang ve dir özniteliklerini yönetebilirsiniz. Bu, sunucuda ve istemcide doğru özniteliklerin ayarlanmasını sağlar.

    src/routes/__root.tsx
    Kodu kopyala

    Kodu panoya kopyala

    function RootDocument({ children }: { children: ReactNode }) {  const params = LocaleRoute.useParams();  const locale = params?.locale ?? defaultLocale;  return (    <html dir={getHTMLTextDir(locale)} lang={locale}>      {/* ... */}    </html>  );}

    Adım 12: Middleware Ekleme (İsteğe Bağlı)

    Uygulamanıza sunucu tarafı yönlendirme eklemek için intlayerProxy'i de kullanabilirsiniz. Bu eklenti, URL'ye göre mevcut yerel ayarı otomatik olarak algılar ve uygun yerel ayar çerezini ayarlar. Hiçbir yerel ayar belirtilmemişse, eklenti kullanıcının tarayıcı dil tercihlerine göre en uygun yerel ayarı belirler. Hiçbir yerel ayar algılanmazsa, varsayılan yerel ayara yönlendirme yapar.

    Üretimde intlayerProxy kullanmak için, vite-intlayer paketini devDependencies'den dependencies'e geçirmeniz gerektiğini unutmayın.
    vite.config.ts
    Kodu kopyala

    Kodu panoya kopyala

    import { tanstackStart } from "@tanstack/react-start/plugin/vite";import viteReact from "@vitejs/plugin-react";import { nitro } from "nitro/vite";import { defineConfig } from "vite";import { intlayer, intlayerProxy } from "vite-intlayer";export default defineConfig({  plugins: [    intlayerProxy(), // Nitro kullanıyorsanız, proxy sunucudan önce yerleştirilmelidir    nitro(),    intlayer(),    tanstackStart({      router: {        routeFileIgnorePattern:          ".content.(ts|tsx|js|mjs|cjs|jsx|json|jsonc|json5)$",      },    }),    viteReact(),  ],});

    Adım 13: Meta Verilerinizi Uluslararasılaştırın (İsteğe Bağlı)

    Uygulamanız genelinde içerik sözlüklerinize erişmek için getIntlayer hook'unu da kullanabilirsiniz:

    src/routes/{-$locale}/index.tsx
    Kodu kopyala

    Kodu panoya kopyala

    import { createFileRoute } from "@tanstack/react-router";import { getIntlayer } from "intlayer";export const Route = createFileRoute("/{-$locale}/")({  component: RouteComponent,  head: ({ params }) => {    const { locale } = params;    const path = "/"; // The path for this route    const metaContent = getIntlayer("app", locale);    return {      links: [        // Canonical link: Points to the current localized page        { rel: "canonical", href: getLocalizedUrl(path, locale) },        // Hreflang: Tell Google about all localized versions        ...localeMap(({ locale: mapLocale }) => ({          rel: "alternate",          hrefLang: mapLocale,          href: getLocalizedUrl(path, mapLocale),        })),        // x-default: For users in unmatched languages        // Define the default fallback locale (usually your primary language)        {          rel: "alternate",          hrefLang: "x-default",          href: getLocalizedUrl(path, defaultLocale),        },      ],      meta: [        { title: metaContent.title },        { name: "description", content: metaContent.meta.description },      ],    };  },});

    Adım 14: Sunucu işlemlerinde yerel ayarı alma (İsteğe Bağlı)

    Sunucu işlemleriniz veya API uç noktalarınızın içinden mevcut yerel ayara erişmek isteyebilirsiniz. Bunu intlayer paketinden getLocale yardımcısını kullanarak yapabilirsiniz.

    TanStack Start'ın sunucu fonksiyonlarını kullanan bir örnek:

    src/routes/{-$locale}/index.tsx
    Kodu kopyala

    Kodu panoya kopyala

    import { createServerFn } from "@tanstack/react-start";import {  getRequestHeader,  getRequestHeaders,} from "@tanstack/react-start/server";import { getCookie, getIntlayer, getLocale } from "intlayer";export const getLocaleServer = createServerFn().handler(async () => {  const locale = await getLocale({    // İstekten çerezi al (varsayılan: 'INTLAYER_LOCALE')    getCookie: (name) => {      const cookieString = getRequestHeader("cookie");      return getCookie(name, cookieString);    },    // İstekten başlığı al (varsayılan: 'x-intlayer-locale')    // Accept-Language anlaşmasını kullanarak geri dönüş    getHeader: (name) => getRequestHeader(name),  });  // getIntlayer() kullanarak bazı içerikleri al  const content = getIntlayer("app", locale);  return { locale, content };});

    Adım 15: Bulunamayan sayfaları yönetme (İsteğe Bağlı)

    Bir kullanıcı var olmayan bir sayfayı ziyaret ettiğinde, özel bir bulunamadı sayfası gösterebilirsiniz ve yerel ayar öneki, bulunamadı sayfasının tetiklenme şeklini etkileyebilir.

    TanStack Router'ın Yerel Ayar Önekleriyle 404 İşlemesini Anlama

    TanStack Router'da yerelleştirilmiş rotalarla 404 sayfalarını işlemek, çok katmanlı bir yaklaşım gerektirir:

    1. Özel 404 rotası: 404 kullanıcı arayüzünü göstermek için özel bir rota
    2. Rota düzeyinde doğrulama: Yerel ayar öneklerini doğrular ve geçersiz olanları 404'e yönlendirir
    3. Catch-all rotası: Yerel ayar segmenti içindeki eşleşmeyen tüm yolları yakalar
    src/routes/{-$locale}/404.tsx
    Kodu kopyala

    Kodu panoya kopyala

    import { createFileRoute } from "@tanstack/react-router";// Bu, özel bir /[locale]/404 rotası oluşturur// Hem doğrudan bir rota olarak kullanılır hem de diğer dosyalarda bir bileşen olarak içe aktarılırexport const Route = createFileRoute("/{-$locale}/404")({  component: NotFoundComponent,});// notFoundComponent ve catch-all rotalarında yeniden kullanılabilmesi için ayrı olarak dışa aktarılırexport function NotFoundComponent() {  return (    <div>      <h1>404</h1>    </div>  );}
    src/routes/{-$locale}/route.tsx
    Kodu kopyala

    Kodu panoya kopyala

    import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";import { validatePrefix } from "intlayer";import { NotFoundComponent } from "./404";export const Route = createFileRoute("/{-$locale}")({  // beforeLoad, rota render edilmeden önce çalışır (hem sunucuda hem de istemcide)  // Yerel ayar önekini doğrulamak için ideal yerdir  beforeLoad: ({ params }) => {    const localeParam = params.locale;    // validatePrefix, yerel ayarın intlayer yapılandırmanıza göre geçerli olup olmadığını kontrol eder    const { isValid, localePrefix } = validatePrefix(localeParam);    if (!isValid) {      // Geçersiz yerel ayar öneki - Geçerli bir yerel ayar öneki ile 404 sayfasına yönlendir      throw redirect({        to: "/{-$locale}/404",        params: { locale: localePrefix },      });    }  },  component: Outlet,  // notFoundComponent, bir alt rota mevcut olmadığında çağrılır  // örn. /en/var-olmayan-sayfa bunu /en düzeni içinde tetikler  notFoundComponent: NotFoundComponent,});
    src/routes/{-$locale}/$.tsx
    Kodu kopyala

    Kodu panoya kopyala

    import { createFileRoute } from "@tanstack/react-router";import { NotFoundComponent } from "./404";// $ (splat/catch-all) rotası, diğer rotalarla eşleşmeyen herhangi bir yolu eşleştirir// örn. /en/bazı/derin/iç içe/geçersiz/yol// Bu, bir yerel ayar içindeki TÜM eşleşmeyen yolların 404 sayfasını göstermesini sağlar// Bu olmadan, eşleşmeyen derin yollar boş bir sayfa veya hata gösterebilirexport const Route = createFileRoute("/{-$locale}/$")({  component: NotFoundComponent,});

    Adım 16: TypeScript Yapılandırması (İsteğe Bağlı)

    Intlayer, TypeScript'in avantajlarından yararlanmak ve kod tabanınızı daha güçlü hale getirmek için modül genişletme (module augmentation) kullanır.

    TypeScript yapılandırmanızın otomatik oluşturulan türleri içerdiğinden emin olun:

    tsconfig.json
    Kodu kopyala

    Kodu panoya kopyala

    {  // ... mevcut yapılandırmalarınız  include: [    // ... mevcut dahil ettikleriniz    ".intlayer/**/*.ts", // Otomatik oluşturulan türleri dahil et  ],}

    (İsteğe bağlı) Adım 17 : Bileşenlerinizin içeriğini çıkarın

    Mevcut bir kod tabanınız varsa, binlerce dosyayı dönüştürmek zaman alıcı olabilir.

    Bu süreci kolaylaştırmak için Intlayer, bileşenlerinizi dönüştürmek ve içeriği çıkarmak için bir derleyici / çıkarıcı sunar.

    Kurulum için intlayer.config.ts dosyanıza bir compiler bölümü ekleyebilirsiniz:

    intlayer.config.ts
    Kodu kopyala

    Kodu panoya kopyala

    import { type IntlayerConfig } from "intlayer";
    
    const config: IntlayerConfig = {
      // ... Yapılandırmanızın geri kalanı
      compiler: {
        /**
         * Derleyicinin etkinleştirilip etkinleştirilmeyeceğini belirtir.
         */
        enabled: true,
    
        /**
         * Çıktı dosyalarının yolunu tanımlar
         */
        output: ({ fileName, extension }) => `./${fileName}${extension}`,
    
        /**
         * Bileşenlerin dönüştürüldükten sonra kaydedilip kaydedilmeyeceğini belirtir. Bu sayede derleyici, uygulamayı dönüştürmek için yalnızca bir kez çalıştırılabilir ve ardından kaldırılabilir.
         */
        saveComponents: false,
    
        /**
         * Sözlük anahtarı öneki
         */
        dictionaryKeyPrefix: "",
      },
    };
    
    export default config;

    Bileşenlerinizi dönüştürmek ve içeriği çıkarmak için çıkarıcıyı çalıştırın

    bash
    Kodu kopyala

    Kodu panoya kopyala

    npx intlayer extract

    vite.config.ts dosyanızı intlayerCompiler eklentisini içerecek şekilde güncelleyin:

    vite.config.ts
    Kodu kopyala

    Kodu panoya kopyala

    import { defineConfig } from "vite";import { intlayer, intlayerCompiler } from "vite-intlayer";export default defineConfig({ plugins: [   intlayer(),   intlayerCompiler(), // Derleyici eklentisini ekler ],});
    bash
    Kodu kopyala

    Kodu panoya kopyala

    npm run build # Veya npm run dev

    Git Yapılandırması

    Intlayer tarafından oluşturulan dosyaların göz ardı edilmesi önerilir. Bu, bu dosyaların Git deposuna eklenmesini önlemenizi sağlar.

    Bunu yapmak için, .gitignore dosyanıza aşağıdaki talimatları ekleyebilirsiniz:

    .gitignore
    Kodu kopyala

    Kodu panoya kopyala

    # Intlayer tarafından oluşturulan dosyaları yoksay.intlayer

    VS Code Eklentisi

    Intlayer ile geliştirme deneyiminizi iyileştirmek için resmi Intlayer VS Code Eklentisini yükleyebilirsiniz.

    VS Code Marketplace'ten Yükleyin

    Bu eklenti şunları sağlar:

    • Çeviri anahtarları için Otomatik tamamlama.
    • Eksik çeviriler için Gerçek zamanlı hata tespiti.
    • Çevrilmiş içeriğin Satır içi önizlemeleri.
    • Çevirileri kolayca oluşturup güncellemek için Hızlı işlemler.

    Bu eklentinin nasıl kullanılacağı hakkında daha fazla detay için, Intlayer VS Code Eklentisi dokümantasyonuna bakabilirsiniz.


    Daha İleri Gitmek

    Daha ileri gitmek için, görsel editörü uygulayabilir veya içeriğinizi CMS kullanarak dışa aktarabilirsiniz.


    Dokümantasyon Referansları

    • Intlayer Dokümantasyonu
    • Tanstack Start Dokümantasyonu
    • useIntlayer hook
    • useLocale hook
    • İçerik Beyanı
    • Yapılandırma
    Derleyici
    Tanstack Start Solid
    Alt+→

    Bu sayfada

      Tartışmalar anonimdir ve yaygın sorunları ele almak için düzenli olarak incelenir. Özellik fikirleri, belgeleme hakkında geri bildirimler veya Intlayer ile ilgili herhangi bir şeyi paylaşmaktan çekinmeyin, bu girdileri yol haritamızı şekillendirmek ve ürünü geliştirmek için kullanıyoruz.

      npm install intlayer react-intlayernpm install vite-intlayer --save-devnpx intlayer init
      import type { IntlayerConfig } from "intlayer";import { Locales } from "intlayer";const config: IntlayerConfig = {  internationalization: {    defaultLocale: Locales.ENGLISH,    locales: [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH],  },};export default config;
      import { tanstackStart } from "@tanstack/react-start/plugin/vite";import viteReact from "@vitejs/plugin-react";import { nitro } from "nitro/vite";import { defineConfig } from "vite";import { intlayer } from "vite-intlayer";const config = defineConfig({  plugins: [    nitro(),    intlayer(),    tanstackStart({      router: {        routeFileIgnorePattern:          ".content.(ts|tsx|js|mjs|cjs|jsx|json|jsonc|json5)$",      },    }),    viteReact(),  ],});export default config;
      import {  createRootRouteWithContext,  HeadContent,  Scripts,} from "@tanstack/react-router";import { defaultLocale, getHTMLTextDir } from "intlayer";import { type ReactNode } from "react";import { IntlayerProvider } from "react-intlayer";import { Route as LocaleRoute } from "./{-$locale}/route";export const Route = createRootRouteWithContext<{}>()({  head: () => ({    meta: [      {        charSet: "utf-8",      },      {        content: "width=device-width, initial-scale=1",        name: "viewport",      },      {        title: "TanStack Start Starter",      },    ],  }),  shellComponent: RootDocument,});function RootDocument({ children }: { children: ReactNode }) {  const params = LocaleRoute.useParams();  const locale = params?.locale ?? defaultLocale;  return (    <html dir={getHTMLTextDir(locale)} lang={locale}>      <head>        <HeadContent />      </head>      <body>        <IntlayerProvider locale={locale}>{children}</IntlayerProvider>        <Scripts />      </body>    </html>  );}
      <img src="{content.image.src.value}" alt="{content.image.value}" /><img src="{content.image.src.toString()}" alt="{content.image.toString()}" /><img src="{String(content.image.src)}" alt="{String(content.image)}" />
      import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";import { validatePrefix } from "intlayer";export const Route = createFileRoute("/{-$locale}")({  beforeLoad: ({ params }) => {    const localeParam = params.locale;    // Yerel ayar ön ekini doğrula    const { isValid, localePrefix } = validatePrefix(localeParam);    if (!isValid) {      throw redirect({        to: "/{-$locale}/404",        params: { locale: localePrefix },      });    }  },  component: Outlet,});
      import type { Dictionary } from "intlayer";import { t } from "intlayer";const appContent = {  content: {    links: {      about: t({        en: "About",        es: "Acerca de",        fr: "À propos",      }),      home: t({        en: "Home",        es: "Inicio",        fr: "Accueil",      }),    },    meta: {      title: t({        en: "Welcome to Intlayer + TanStack Router",        es: "Bienvenido a Intlayer + TanStack Router",        fr: "Bienvenue à Intlayer + TanStack Router",      }),      description: t({        en: "This is an example of using Intlayer with TanStack Router",        es: "Este es un ejemplo de uso de Intlayer con TanStack Router",        fr: "Ceci est un exemple d'utilisation d'Intlayer avec TanStack Router",      }),    },  },  key: "app",} satisfies Dictionary;export default appContent;
      import type { FC } from "react";import { Link, type LinkComponentProps } from "@tanstack/react-router";import { useLocale } from "react-intlayer";import { getPrefix } from "intlayer";export const LOCALE_ROUTE = "{-$locale}" as const;export type To = StripLocalePrefix<LinkComponentProps["to"]>;export type StripLocalePrefix<T extends string | undefined> = T extends  | `/${typeof LOCALE_ROUTE}/`  | `/${typeof LOCALE_ROUTE}`  ? "/"  : T extends `/${typeof LOCALE_ROUTE}/${infer Rest}`    ? `/${Rest}`    : T;type LocalizedLinkProps = {  to?: To;} & Omit<LinkComponentProps, "to">;export const LocalizedLink: FC<LocalizedLinkProps> = (props) => {  const { locale } = useLocale();  const { localePrefix } = getPrefix(locale);  return (    <Link      {...props}      params={{        locale: localePrefix,        ...(typeof props?.params === "object" ? props?.params : {}),      }}      to={`/${LOCALE_ROUTE}${props.to}` as LinkComponentProps["to"]}    />  );};
      import { useNavigate } from "@tanstack/react-router";import { getPrefix } from "intlayer";import { useLocale } from "react-intlayer";import type { StripLocalePrefix } from "@/components/localized-link";import type { FileRouteTypes } from "@/routeTree.gen";type NavigateFn = ReturnType<typeof useNavigate>;type BaseNavigateOptions = Parameters<NavigateFn>[0];type LocalizedTo = StripLocalePrefix<FileRouteTypes["to"]>;export type LocalizedNavigateOptions = Omit<  BaseNavigateOptions,  "to" | "params"> & {  to: LocalizedTo;  params?: Omit<NonNullable<BaseNavigateOptions["params"]>, "locale">;};type LocalizedNavigate = (  options: LocalizedNavigateOptions) => ReturnType<NavigateFn>;export const useLocalizedNavigate = () => {  const navigate = useNavigate();  const { locale } = useLocale();  const localizedNavigate: LocalizedNavigate = (args: any) => {    const { localePrefix } = getPrefix(locale);    if (typeof args === "string") {      return navigate({        to: `/${LOCALE_ROUTE}${args}`,        params: { locale: localePrefix },      });    }    const { to, ...rest } = args;    const localizedTo = `/${LOCALE_ROUTE}${to}` as any;    return navigate({      to: localizedTo,      params: { locale: localePrefix, ...rest } as any,    });  };  return localizedNavigate;};
      import { createFileRoute } from "@tanstack/react-router";import { getIntlayer } from "intlayer";import { useIntlayer } from "react-intlayer";import LocaleSwitcher from "@/components/locale-switcher";import { LocalizedLink } from "@/components/localized-link";import { useLocalizedNavigate } from "@/hooks/useLocalizedNavigate";export const Route = createFileRoute("/{-$locale}/")({  component: RouteComponent,});function RouteComponent() {  const content = useIntlayer("app");  const navigate = useLocalizedNavigate();  return (    <div>      <div>        {content.title}        <LocaleSwitcher />        <div>          <LocalizedLink to="/">{content.links.home}</LocalizedLink>          <LocalizedLink to="/about">{content.links.about}</LocalizedLink>        </div>        <div>          <button onClick={() => navigate({ to: "/" })}>            {content.links.home}          </button>          <button onClick={() => navigate({ to: "/about" })}>            {content.links.about}          </button>        </div>      </div>    </div>  );}
      import { useLocation } from "@tanstack/react-router";import {  getHTMLTextDir,  getLocaleName,  getPathWithoutLocale,  getPrefix,  Locales,} from "intlayer";import type { FC } from "react";import { useLocale } from "react-intlayer";import { LocalizedLink, type To } from "./localized-link";export const LocaleSwitcher: FC = () => {  const { pathname } = useLocation();  const { availableLocales, locale, setLocale } = useLocale();  const pathWithoutLocale = getPathWithoutLocale(pathname);  return (    <ol>      {availableLocales.map((localeEl) => (        <li key={localeEl}>          <LocalizedLink            aria-current={localeEl === locale ? "page" : undefined}            onClick={() => setLocale(localeEl)}            params={{ locale: getPrefix(localeEl).localePrefix }}            to={pathWithoutLocale as To}          >            <span>              {/* Dil Kodu - örn. FR */}              {localeEl}            </span>            <span>              {/* Dil kendi yerelinde - örn. Français */}              {getLocaleName(localeEl, locale)}            </span>            <span dir={getHTMLTextDir(localeEl)} lang={localeEl}>              {/* Dil mevcut yerelde - örn. Francés, mevcut yerel Locales.SPANISH olarak ayarlanmış */}              {getLocaleName(localeEl)}            </span>            <span dir="ltr" lang={Locales.ENGLISH}>              {/* Dil İngilizce olarak - örn. French */}              {getLocaleName(localeEl, Locales.ENGLISH)}            </span>          </LocalizedLink>        </li>      ))}    </ol>  );};
      function RootDocument({ children }: { children: ReactNode }) {  const params = LocaleRoute.useParams();  const locale = params?.locale ?? defaultLocale;  return (    <html dir={getHTMLTextDir(locale)} lang={locale}>      {/* ... */}    </html>  );}
      import { tanstackStart } from "@tanstack/react-start/plugin/vite";import viteReact from "@vitejs/plugin-react";import { nitro } from "nitro/vite";import { defineConfig } from "vite";import { intlayer, intlayerProxy } from "vite-intlayer";export default defineConfig({  plugins: [    intlayerProxy(), // Nitro kullanıyorsanız, proxy sunucudan önce yerleştirilmelidir    nitro(),    intlayer(),    tanstackStart({      router: {        routeFileIgnorePattern:          ".content.(ts|tsx|js|mjs|cjs|jsx|json|jsonc|json5)$",      },    }),    viteReact(),  ],});
      import { createFileRoute } from "@tanstack/react-router";import { getIntlayer } from "intlayer";export const Route = createFileRoute("/{-$locale}/")({  component: RouteComponent,  head: ({ params }) => {    const { locale } = params;    const path = "/"; // The path for this route    const metaContent = getIntlayer("app", locale);    return {      links: [        // Canonical link: Points to the current localized page        { rel: "canonical", href: getLocalizedUrl(path, locale) },        // Hreflang: Tell Google about all localized versions        ...localeMap(({ locale: mapLocale }) => ({          rel: "alternate",          hrefLang: mapLocale,          href: getLocalizedUrl(path, mapLocale),        })),        // x-default: For users in unmatched languages        // Define the default fallback locale (usually your primary language)        {          rel: "alternate",          hrefLang: "x-default",          href: getLocalizedUrl(path, defaultLocale),        },      ],      meta: [        { title: metaContent.title },        { name: "description", content: metaContent.meta.description },      ],    };  },});
      import { createServerFn } from "@tanstack/react-start";import {  getRequestHeader,  getRequestHeaders,} from "@tanstack/react-start/server";import { getCookie, getIntlayer, getLocale } from "intlayer";export const getLocaleServer = createServerFn().handler(async () => {  const locale = await getLocale({    // İstekten çerezi al (varsayılan: 'INTLAYER_LOCALE')    getCookie: (name) => {      const cookieString = getRequestHeader("cookie");      return getCookie(name, cookieString);    },    // İstekten başlığı al (varsayılan: 'x-intlayer-locale')    // Accept-Language anlaşmasını kullanarak geri dönüş    getHeader: (name) => getRequestHeader(name),  });  // getIntlayer() kullanarak bazı içerikleri al  const content = getIntlayer("app", locale);  return { locale, content };});
      import { createFileRoute } from "@tanstack/react-router";// Bu, özel bir /[locale]/404 rotası oluşturur// Hem doğrudan bir rota olarak kullanılır hem de diğer dosyalarda bir bileşen olarak içe aktarılırexport const Route = createFileRoute("/{-$locale}/404")({  component: NotFoundComponent,});// notFoundComponent ve catch-all rotalarında yeniden kullanılabilmesi için ayrı olarak dışa aktarılırexport function NotFoundComponent() {  return (    <div>      <h1>404</h1>    </div>  );}
      import { createFileRoute, Outlet, redirect } from "@tanstack/react-router";import { validatePrefix } from "intlayer";import { NotFoundComponent } from "./404";export const Route = createFileRoute("/{-$locale}")({  // beforeLoad, rota render edilmeden önce çalışır (hem sunucuda hem de istemcide)  // Yerel ayar önekini doğrulamak için ideal yerdir  beforeLoad: ({ params }) => {    const localeParam = params.locale;    // validatePrefix, yerel ayarın intlayer yapılandırmanıza göre geçerli olup olmadığını kontrol eder    const { isValid, localePrefix } = validatePrefix(localeParam);    if (!isValid) {      // Geçersiz yerel ayar öneki - Geçerli bir yerel ayar öneki ile 404 sayfasına yönlendir      throw redirect({        to: "/{-$locale}/404",        params: { locale: localePrefix },      });    }  },  component: Outlet,  // notFoundComponent, bir alt rota mevcut olmadığında çağrılır  // örn. /en/var-olmayan-sayfa bunu /en düzeni içinde tetikler  notFoundComponent: NotFoundComponent,});
      import { createFileRoute } from "@tanstack/react-router";import { NotFoundComponent } from "./404";// $ (splat/catch-all) rotası, diğer rotalarla eşleşmeyen herhangi bir yolu eşleştirir// örn. /en/bazı/derin/iç içe/geçersiz/yol// Bu, bir yerel ayar içindeki TÜM eşleşmeyen yolların 404 sayfasını göstermesini sağlar// Bu olmadan, eşleşmeyen derin yollar boş bir sayfa veya hata gösterebilirexport const Route = createFileRoute("/{-$locale}/$")({  component: NotFoundComponent,});
      {  // ... mevcut yapılandırmalarınız  include: [    // ... mevcut dahil ettikleriniz    ".intlayer/**/*.ts", // Otomatik oluşturulan türleri dahil et  ],}
      npx intlayer extract
      import { defineConfig } from "vite";import { intlayer, intlayerCompiler } from "vite-intlayer";export default defineConfig({ plugins: [   intlayer(),   intlayerCompiler(), // Derleyici eklentisini ekler ],});
      npm run build # Veya npm run dev
      # Intlayer tarafından oluşturulan dosyaları yoksay.intlayer