Questa pagina ha un modello di applicazione disponibile.
Pose una domanda e ottieni un riassunto del documento facendo riferimento a questa pagina e al provider AI di tua scelta
Integrando il server MCP Intlayer al tuo assistente AI, puoi recuperare tutti i documenti direttamente da ChatGPT, DeepSeek, Cursor, VSCode, ecc.
Vedi la documentazione del server MCPIl contenuto di questa pagina è stato tradotto con un'IA.
Vedi l'ultima versione del contenuto originale in ingleseSe hai un’idea per migliorare questa documentazione, non esitare a contribuire inviando una pull request su GitHub.
Collegamento GitHub alla documentazioneCopia il Markdown del documento nella porta-documenti
Getting Started Internationalizing (i18n) with Intlayer and React Router v7
This guide demonstrates how to integrate Intlayer for seamless internationalization in React Router v7 projects with locale-aware routing, TypeScript support, and modern development practices.
What is Intlayer?
Intlayer is an innovative, open-source internationalization (i18n) library designed to simplify multilingual support in modern web applications.
With Intlayer, you can:
- Easily manage translations using declarative dictionaries at the component level.
- Dynamically localize metadata, routes, and content.
- Ensure TypeScript support with autogenerated types, improving autocompletion and error detection.
- Benefit from advanced features, like dynamic locale detection and switching.
- Enable locale-aware routing with React Router v7's configuration-based routing system.
Step-by-Step Guide to Set Up Intlayer in a React Router v7 Application
Step 1: Install Dependencies
Install the necessary packages using your preferred package manager:
Copiare il codice nella clipboard
npm install intlayer react-intlayernpm install vite-intlayer --save-dev
intlayer
The core package that provides internationalization tools for configuration management, translation, content declaration, transpilation, and CLI commands.
react-intlayer The package that integrates Intlayer with React application. It provides context providers and hooks for React internationalization.
vite-intlayer Includes the Vite plugin for integrating Intlayer with the Vite bundler, as well as middleware for detecting the user's preferred locale, managing cookies, and handling URL redirection.
Step 2: Configuration of your project
Create a config file to configure the languages of your application:
Copiare il codice nella clipboard
import { type IntlayerConfig, Locales } from "intlayer";const config: IntlayerConfig = { internationalization: { defaultLocale: Locales.ENGLISH, locales: [Locales.ENGLISH, Locales.TURKISH], }, middleware: { prefixDefault: true, // Always prefix default locale in URLs },};export default config;
Through this configuration file, you can set up localized URLs, middleware redirection, cookie names, the location and extension of your content declarations, disable Intlayer logs in the console, and more. For a complete list of available parameters, refer to the configuration documentation.
Step 3: Configure React Router v7 Routes
Set up your routing configuration with locale-aware routes:
Copiare il codice nella clipboard
import { layout, route, type RouteConfig } from "@react-router/dev/routes";export default [ layout("routes/layout.tsx", [ route("/", "routes/page.tsx"), // Root page - redirects to locale route("/:lang", "routes/[lang]/page.tsx"), // Localized home page route("/:lang/about", "routes/[lang]/about/page.tsx"), // Localized about page ]),] satisfies RouteConfig;
Step 4: Integrate Intlayer in Your Vite Configuration
Add the intlayer plugin into your configuration:
Copiare il codice nella clipboard
import { reactRouter } from "@react-router/dev/vite";import { defineConfig } from "vite";import { intLayerMiddlewarePlugin, intlayerPlugin } from "vite-intlayer";import tsconfigPaths from "vite-tsconfig-paths";export default defineConfig({ plugins: [ reactRouter(), tsconfigPaths(), intlayerPlugin(), intLayerMiddlewarePlugin(), ],});
The intlayerPlugin() Vite plugin is used to integrate Intlayer with Vite. It ensures the building of content declaration files and monitors them in development mode. It defines Intlayer environment variables within the Vite application. Additionally, it provides aliases to optimize performance.
Step 5: Create Layout Components
Set up your root layout and locale-specific layouts:
Root Layout
Copiare il codice nella clipboard
// app/routes/layout.tsximport { Outlet } from "react-router";import { IntlayerProvider } from "react-intlayer";export default function RootLayout() { return ( <IntlayerProvider> <Outlet /> </IntlayerProvider> );}
Step 6: Declare Your Content
Create and manage your content declarations to store translations:
Copiare il codice nella clipboard
import { t, type Dictionary } from "intlayer";const pageContent = { key: "page", content: { title: t({ en: "Welcome to React Router v7 + Intlayer", tr: "React Router v7 + Intlayer'a Hoş Geldiniz", }), description: t({ en: "Build multilingual applications with ease using React Router v7 and Intlayer.", tr: "React Router v7 ve Intlayer kullanarak kolayca çok dilli uygulamalar geliştirin.", }), aboutLink: t({ en: "Learn About Us", tr: "Hakkımızda Öğrenin", }), homeLink: t({ en: "Home", tr: "Ana Sayfa", }), },} satisfies Dictionary;export default pageContent;
Your content declarations can be defined anywhere in your application as soon they are included into the contentDir directory (by default, ./app). And match the content declaration file extension (by default, .content.{json,ts,tsx,js,jsx,mjs,mjx,cjs,cjx}).
For more details, refer to the content declaration documentation.
Step 7: Create Locale-Aware Components
Create a LocalizedLink component for locale-aware navigation:
Copiare il codice nella clipboard
// app/components/localized-link.tsximport { getLocalizedUrl } from "intlayer";import { useLocale } from "react-intlayer";import React from "react";import { Link, useLocation } from "react-router";type RouterLinkProps = React.ComponentProps<typeof Link>;export default function LocalizedLink({ to, ...props }: RouterLinkProps) { const { locale } = useLocale(); const location = useLocation(); const isExternal = (path: string) => /^([a-z][a-z0-9+.-]*:)?\/\//i.test(path) || path.startsWith("mailto:"); if (typeof to === "string") { if (to.startsWith("/") && !isExternal(to)) { return <Link to={getLocalizedUrl(to, locale)} {...props} />; } return <Link to={to} {...props} />; } if (to && typeof to === "object") { const pathname = (to as { pathname?: string }).pathname; if (pathname && pathname.startsWith("/") && !isExternal(pathname)) { return ( <Link to={{ ...to, pathname: getLocalizedUrl(pathname, locale) }} {...props} /> ); } return <Link to={to} {...props} />; } return ( <Link to={getLocalizedUrl(location.pathname + location.search, locale)} {...props} /> );}
Step 8: Utilize Intlayer in Your Pages
Access your content dictionaries throughout your application:
Root Redirect Page
Copiare il codice nella clipboard
// app/routes/page.tsximport { useLocale } from "react-intlayer";import { Navigate } from "react-router";export default function Page() { const { locale } = useLocale(); return <Navigate replace to={locale} />;}
Localized Home Page
Copiare il codice nella clipboard
import { useIntlayer } from "react-intlayer";import LocalizedLink from "~/components/localized-link";export default function Page() { const content = useIntlayer("page"); return ( <div style={{ padding: "2rem", textAlign: "center" }}> <h1>{content.title}</h1> <p>{content.description}</p> <nav style={{ marginTop: "2rem" }}> <LocalizedLink to="/about" style={{ display: "inline-block", padding: "0.5rem 1rem", backgroundColor: "#007bff", color: "white", textDecoration: "none", borderRadius: "4px", }} > {content.aboutLink} </LocalizedLink> </nav> </div> );}
To Learn more about the useIntlayer hook, refer to the documentation.
Step 9: Create a Locale Switcher Component
Create a component to allow users to change languages:
Copiare il codice nella clipboard
import { getLocalizedUrl, getLocaleName } from "intlayer";import { useLocale } from "react-intlayer";import { useLocation, useNavigate } from "react-router";export default function LocaleSwitcher() { const { locale, availableLocales, setLocale } = useLocale(); const location = useLocation(); const navigate = useNavigate(); const handleLocaleChange = (newLocale: string) => { const localizedUrl = getLocalizedUrl( location.pathname + location.search, newLocale ); setLocale(newLocale); navigate(localizedUrl); }; return ( <div style={{ margin: "1rem 0" }}> <label htmlFor="locale-select">Choose Language: </label> <select id="locale-select" value={locale} onChange={(e) => handleLocaleChange(e.target.value)} style={{ padding: "0.25rem", marginLeft: "0.5rem" }} > {availableLocales.map((availableLocale) => ( <option key={availableLocale} value={availableLocale}> {getLocaleName(availableLocale)} </option> ))} </select> </div> );}
To Learn more about the useLocale hook, refer to the documentation.
Step 10: Add HTML Attributes Management (Optional)
Create a hook to manage HTML lang and dir attributes:
Copiare il codice nella clipboard
// app/hooks/useI18nHTMLAttributes.tsximport { getHTMLTextDir } from "intlayer";import { useEffect } from "react";import { useLocale } from "react-intlayer";export const useI18nHTMLAttributes = () => { const { locale } = useLocale(); useEffect(() => { document.documentElement.lang = locale; document.documentElement.dir = getHTMLTextDir(locale); }, [locale]);};
Then use it in your root component:
Copiare il codice nella clipboard
// app/routes/layout.tsximport { Outlet } from "react-router";import { IntlayerProvider } from "react-intlayer";import { useI18nHTMLAttributes } from "app/hooks/useI18nHTMLAttributes"; // import the hookexport default function RootLayout() { useI18nHTMLAttributes(); // call the hook return ( <IntlayerProvider> <Outlet /> </IntlayerProvider> );}
Step 11: Build and Run Your Application
Build the content dictionaries and run your application:
Copiare il codice nella clipboard
# Build Intlayer dictionariesnpm run intlayer:build# Start development servernpm run dev
Step 12: Configure TypeScript (Optional)
Intlayer uses module augmentation to get benefits of TypeScript and make your codebase stronger.
Ensure your TypeScript configuration includes the autogenerated types:
Copiare il codice nella clipboard
{ compilerOptions: { // ... your existing TypeScript configurations }, include: [ // ... your existing includes ".intlayer/**/*.ts", // Include the auto-generated types ],}
Git Configuration
It is recommended to ignore the files generated by Intlayer. This allows you to avoid committing them to your Git repository.
To do this, you can add the following instructions to your .gitignore file:
Copiare il codice nella clipboard
# Ignore the files generated by Intlayer.intlayer
Production Deployment
When deploying your application:
Build your application:
bashCopiare il codiceCopiare il codice nella clipboard
npm run build
Build Intlayer dictionaries:
bashCopiare il codiceCopiare il codice nella clipboard
npm run intlayer:build
Move vite-intlayer to dependencies if using middleware in production:
bashCopiare il codiceCopiare il codice nella clipboard
npm install vite-intlayer --save
Your application will now support:
- URL Structure: /en, /en/about, /tr, /tr/about
- Automatic locale detection based on browser preferences
- Locale-aware routing with React Router v7
- TypeScript support with auto-generated types
- Server-side rendering with proper locale handling
VS Code Extension
To improve your development experience with Intlayer, you can install the official Intlayer VS Code Extension.
Install from the VS Code Marketplace
This extension provides:
- Autocompletion for translation keys.
- Real-time error detection for missing translations.
- Inline previews of translated content.
- Quick actions to easily create and update translations.
For more details on how to use the extension, refer to the Intlayer VS Code Extension documentation.
Go Further
To go further, you can implement the visual editor or externalize your content using the CMS.
Documentation References
- Intlayer Documentation
- React Router v7 Documentation
- useIntlayer hook
- useLocale hook
- Content Declaration
- Configuration
This comprehensive guide provides everything you need to integrate Intlayer with React Router v7 for a fully internationalized application with locale-aware routing and TypeScript support.
Doc History
Version | Date | Changes |
---|---|---|
5.8.2 | 2025-09-4 | Added for React Router v7 |