Tác giả:
    Ngày tạo:2026-11-23Cập nhật lần cuối:2026-11-23

    Di chuyển từ react-intl (FormatJS) sang Intlayer

    Tại sao nên chuyển từ react-intl sang Intlayer?

    Với react-intl, mọi thông điệp của locale được truyền vào IntlProvider, nên mỗi trang mang theo toàn bộ catalog. Intlayer chỉ gửi các từ điển mà mỗi trang sử dụng, giúp giảm kích thước bundle và trang tới 50%.

    Id thông điệp được định kiểu theo từ điển của bạn: id không hợp lệ sẽ lỗi khi build. Nội dung có thể đặt cạnh các component sử dụng nó.

    Nội dung đặt cạnh component giảm ngữ cảnh cần thiết cho LLM. Intlayer cung cấp CLI để kiểm tra bản dịch còn thiếu, LSP, máy chủ MCP và agent skills.

    Dịch các thông điệp còn thiếu trong pipeline CI/CD bằng LLM bạn chọn, hoặc chạy nền với nền tảng web.

    Intlayer cung cấp trình chỉnh sửa trực quan tự host và CMS đầy đủ để người dịch và copywriter chỉnh sửa nội dung theo thời gian thực.

    Để hiểu các thư viện này đến từ đâu, hãy đọc lịch sử i18n trong JavaScript.

    Chiến lược di chuyển

    1. Compat adapter (khuyến nghị cho ứng dụng hiện có): cài @intlayer/react-intl. Package này cung cấp cùng API với react-intl (IntlProvider, useIntl, FormattedMessage, FormattedNumber, FormattedDate, defineMessages, createIntl…) và phục vụ thông điệp từ các từ điển Intlayer. ICU MessageFormat, số nhiều, select và thẻ rich text hoạt động như trước.
    2. Di chuyển hoàn toàn: thay dần các lời gọi react-intl bằng useIntlayer và các file .content.ts đặt cạnh component.

    Mục lục

    Di chuyển nhanh

    1. Cài đặt dependency

      bash
      npx intlayer init --interactive
      
      Flag --interactive là tùy chọn. Hãy dùng intlayer-cli init nếu bạn là AI agent.

      Lệnh này phát hiện môi trường của bạn và cài các package cần thiết, ví dụ:

      bash
      npm install intlayer react-intlayer @intlayer/react-intl @intlayer/sync-json-plugin
      
      Giữ react-intl đã cài: nó cung cấp kiểu TypeScript.
    2. Cấu hình Intlayer

      Trỏ plugin syncJSON tới các file thông điệp hiện có. Catalog react-intl là các map phẳng gồm id có dấu chấm:

      src/lang/en.json
      {
        "home.title": "Welcome",
        "home.greeting": "Hello {name}",
        "cart.items": "{count, plural, one {# item} other {# items}}"
      }
      
      intlayer.config.ts
      import { Locales, type IntlayerConfig } from "intlayer";
      import { syncJSON } from "@intlayer/sync-json-plugin";
      
      const config: IntlayerConfig = {
        internationalization: {
          locales: [Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH],
          defaultLocale: Locales.ENGLISH,
        },
        plugins: [
          syncJSON({
            // react-intl uses ICU MessageFormat
            format: "icu",
            source: ({ locale }) => `./src/lang/${locale}.json`,
            // 'home.title' → dictionary `home`, key `title`
            splitKeys: "key-prefix",
          }),
        ],
      };
      
      export default config;
      
      Phân đoạn đầu tiên của mỗi id (home) trở thành một từ điển Intlayer, nên mỗi trang chỉ tải các từ điển nó dùng. Khi Intlayer ghi ngược bản dịch, file vẫn giữ cấu trúc phẳng.
    3. Thêm plugin Vite

      reactIntlVitePlugin() chạy build Intlayer và tạo alias react-intl sang @intlayer/react-intl, không cần thay đổi file nguồn.

      vite.config.ts
      import { defineConfig } from "vite";
      import react from "@vitejs/plugin-react";
      import { reactIntlVitePlugin } from "@intlayer/react-intl/plugin";
      
      export default defineConfig({
        plugins: [react(), reactIntlVitePlugin()],
      });
      
      Dùng bundler khác? Đổi tên import thành @intlayer/react-intl (xem bước 5) và dùng plugin Intlayer cho bundler của bạn, ví dụ withIntlayer từ next-intlayer cho Next.js.
    4. Ngừng truyền thông điệp vào IntlProvider

      IntlProvider vẫn hoạt động, nhưng thông điệp giờ được Intlayer tải. Hãy xóa prop messages và import catalog:

      src/main.tsx
      import { IntlProvider } from "react-intl";
      
      export const App = ({ locale }: { locale: string }) => (
        <IntlProvider locale={locale} defaultLocale="en">
          <Home />
        </IntlProvider>
      );
      
      Nếu messages vẫn được truyền vào, nó sẽ bị bỏ qua và một cảnh báo hiển thị khi phát triển.

    Các component của bạn tiếp tục hoạt động mà không cần thay đổi, với id được định kiểu:

    src/Home.tsx
    import { FormattedMessage, FormattedNumber, useIntl } from "react-intl";
    
    export const Home = () => {
      const intl = useIntl();
    
      return (
        <main>
          <h1>{intl.formatMessage({ id: "home.title" })}</h1>
          <FormattedMessage id="home.greeting" values={{ name: "Ada" }} />
          <FormattedNumber value={42} style="currency" currency="EUR" />
        </main>
      );
    };
    

    Di chuyển hoàn toàn

    1. Đổi tên import tường minh (tùy chọn)

      Tùy chọn

      Plugin Vite đã xử lý alias. Để thể hiện dependency một cách tường minh:

      TrướcSau
      import { IntlProvider } from 'react-intl'import { IntlProvider } from '@intlayer/react-intl'
      import { useIntl } from 'react-intl'import { useIntl } from '@intlayer/react-intl'
      import { FormattedMessage } from 'react-intl'import { FormattedMessage } from '@intlayer/react-intl'
      import { defineMessages } from 'react-intl'import { defineMessages } from '@intlayer/react-intl'
      import { createIntl } from 'react-intl'import { createIntl } from '@intlayer/react-intl'
    2. Chuyển nội dung sang file .content.ts

      Tùy chọn

      Các component mới có thể dùng nội dung Intlayer gốc, song song với các lời gọi react-intl hiện có:

      src/home.content.ts
      import { t, type Dictionary } from "intlayer";
      
      const homeContent = {
        key: "home",
        content: {
          title: t({ en: "Welcome", fr: "Bienvenue", es: "Bienvenido" }),
        },
      } satisfies Dictionary;
      
      export default homeContent;
      
      src/Home.tsx
      import { useIntlayer } from "react-intlayer";
      
      export const Home = () => {
        const { title } = useIntlayer("home");
      
        return <h1>{title}</h1>;
      };
      
    3. Bật dịch bằng AI

      Tùy chọn
      bash
      # Test for missing translations (add to CI)
      npx intlayer test
      
      # Fill missing translations with AI
      npx intlayer fill
      

      Các bản dịch được điền sẽ ghi ngược lại vào các file JSON của bạn. Xem tài liệu CLI để cấu hình AI.

    Những gì có thể xóa sau khi di chuyển

    File / mẫuLý do không còn cần
    Prop messages và việc tải catalogTừ điển được Intlayer biên dịch và tải.
    Bước formatjs compileIntlayer phân tích thông điệp ICU trực tiếp từ file JSON.
    Sinh id bằng babel-plugin-formatjsDùng id tường minh có dấu chấm để mỗi id ánh xạ tới một từ điển.

    Cấu hình TypeScript

    Thêm các kiểu được sinh ra vào tsconfig.json:

    tsconfig.json
    {
      "include": [
        // ... your existing paths
        ".intlayer/**/*.ts",
      ],
    }
    

    Cấu hình Git

    .gitignore
    # Ignore the files generated by Intlayer
    .intlayer
    

    Go Further