이 페이지와 원하는 AI 어시스턴트를 사용하여 문서를 요약합니다
버전 기록
- "Solid useIntlayer API 사용법을 직접 속성 액세스로 업데이트"v8.9.02026. 5. 4.
- "init 명령어 추가"v7.5.92025. 12. 30.
- "Astro 통합, 설정 및 사용법 업데이트"v6.2.02025. 10. 3.
이 페이지의 콘텐츠는 AI를 사용하여 번역되었습니다.
영어 원본 내용의 최신 버전을 보기If you have an idea for improving this documentation, please feel free to contribute by submitting a pull request on GitHub.
GitHub link to the documentationCopy doc Markdown to clipboard
Intlayer를 사용하여 Astro 사이트 번역하기 | 국제화 (i18n)
목차
대안보다 Intlayer를 선택해야 하는 이유는 무엇입니까?
'astro-i18n' 또는 'i18next'와 같은 주요 솔루션과 비교할 때 Intlayer는 다음과 같은 통합 최적화가 제공되는 솔루션입니다.
Intlayer는 다국어 라우팅, 사이트맵 및 국제화 확장(i18n)에 필요한 모든 기능을 제공하여 Astro와 완벽하게 작동하도록 최적화되어 있습니다.
대용량 JSON 파일을 페이지에 로드하는 대신 필요한 콘텐츠만 로드하세요. Intlayer는 번들 및 페이지 크기를 최대 50% 줄이는 데 도움이 됩니다.
애플리케이션 콘텐츠의 범위를 지정하면 대규모 애플리케이션의 유지 관리가 용이해집니다. 전체 콘텐츠 코드베이스를 검토해야 하는 정신적 부담 없이 단일 기능 폴더를 복제하거나 삭제할 수 있습니다. 또한 Intlayer는 완전히 유형되어 콘텐츠의 정확성을 보장합니다.
콘텐츠를 같은 위치에 배치하면 LLM(대형 언어 모델)에 필요한 컨텍스트가 줄어듭니다. Intlayer에는 누락된 번역을 테스트하기 위한 CLI, LSP, MCP 및 agent)와 같은 도구 모음도 함께 제공됩니다. 기술, AI 에이전트를 위한 개발자 경험(DX)을 더욱 원활하게 만듭니다.
AI 공급자의 비용으로 선택한 LLM을 사용하여 CI/CD 파이프라인을 번역하려면 자동화를 사용하세요. Intlayer는 또한 콘텐츠 추출을 자동화하는 컴파일러와 백그라운드에서 번역을 돕는 웹 플랫폼을 제공합니다.
대규모 JSON 파일을 구성 요소에 연결하면 성능 및 반응성 문제가 발생할 수 있습니다. Intlayer는 빌드 시 콘텐츠 로딩을 최적화합니다.
Astro에서 Intlayer 설정을 위한 단계별 가이드
GitHub에서 애플리케이션 템플릿 보기.
종속성 설치
선호하는 패키지 관리자를 사용하여 필요한 패키지를 설치합니다:
bash코드 복사코드를 클립보드에 복사
npm install intlayer astro-intlayer# 선택 사항: React 아일랜드 지원 추가 시npm install react react-dom react-intlayer @astrojs/react프로젝트 설정
애플리케이션의 언어를 설정하기 위한 설정 파일을 생성합니다:
intlayer.config.ts코드 복사코드를 클립보드에 복사
import { Locales, type IntlayerConfig } from "intlayer";const config: IntlayerConfig = { internationalization: { locales: [ Locales.ENGLISH, Locales.FRENCH, Locales.SPANISH, // 기타 로케일 ], defaultLocale: Locales.ENGLISH, },};export default config;이 설정 파일을 통해 로컬라이즈된 URL, 미들웨어 리디렉션, 쿠키 이름, 콘텐츠 선언 위치 및 확장자 설정, 콘솔의 Intlayer 로그 비활성화 등을 구성할 수 있습니다. 사용 가능한 파라미터의 전체 목록은 설정 문서를 참조하세요.
Astro 설정에 Intlayer 통합
Astro 설정에 intlayer 플러그인을 추가합니다.
astro.config.ts코드 복사코드를 클립보드에 복사
// @ts-checkimport { intlayer } from "astro-intlayer";import { defineConfig } from "astro/config";// https://astro.build/configexport default defineConfig({ integrations: [intlayer()],});intlayer()통합 플러그인은 Intlayer를 Astro와 통합하는 데 사용됩니다. 콘텐츠 선언 파일의 빌드를 보장하고 개발 모드에서 이를 감시합니다. Astro 애플리케이션 내에서 Intlayer 환경 변수를 정의하며, 성능 최적화를 위한 에일리어스(alias)를 제공합니다.콘텐츠 선언
번역을 저장하기 위해 콘텐츠 선언을 생성하고 관리합니다:
src/app.content.tsx코드 복사코드를 클립보드에 복사
import { t, type Dictionary } from "intlayer";import type { ReactNode } from "react";const appContent = { key: "app", content: { title: t({ en: "Hello World", fr: "Bonjour le monde", es: "Hola mundo", ko: "안녕하세요", }), },} satisfies Dictionary;export default appContent;콘텐츠 선언은
contentDir(기본값./src)에 포함되어 있고 콘텐츠 선언 파일 확장자(기본값.content.{json,ts,tsx,js,jsx,mjs,cjs,md,mdx,yaml,yml})와 일치한다면 애플리케이션 어디에서나 정의할 수 있습니다.자세한 내용은 콘텐츠 선언 문서를 참조하세요.
Astro에서 콘텐츠 사용
intlayer에서 내보낸 핵심 헬퍼를 사용하여.astro파일에서 직접 사전을 소비할 수 있습니다.src/pages/index.astro코드 복사코드를 클립보드에 복사
---import { getIntlayer, getLocaleFromPath, getLocalizedUrl, defaultLocale, localeMap, getHTMLTextDir, type LocalesValues,} from "intlayer";import LocaleSwitcher from "../components/LocaleSwitcher.astro";// Get the current locale from the URL (e.g. /es/about -> 'es')const locale = getLocaleFromPath(Astro.url.pathname) as LocalesValues;// Get the content for the 'app' dictionaryconst { title } = getIntlayer("app", locale);---<!doctype html><html lang={locale} dir={getHTMLTextDir(locale)}> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <link rel="icon" type="image/svg+xml" href="/favicon.svg" /> <title>{title}</title> <!-- Canonical link: Tells search engines which is the primary version of this page --> <link rel="canonical" href={new URL(getLocalizedUrl(Astro.url.pathname, locale), Astro.site)} /> <!-- Hreflang: Tell Google about all localized versions --> { localeMap(({ locale: mapLocale }) => ( <link rel="alternate" hreflang={mapLocale} href={new URL( getLocalizedUrl(Astro.url.pathname, mapLocale), Astro.site )} /> )) } <!-- x-default: Fallback for users in unmatched languages --> <link rel="alternate" hreflang="x-default" href={new URL( getLocalizedUrl(Astro.url.pathname, defaultLocale), Astro.site )} /> </head> <body> <header> <LocaleSwitcher /> </header> <main> <h1>{title}</h1> </main> </body></html>로컬라이즈된 라우팅
로컬라이즈된 페이지를 제공하기 위해 동적 라우트 세그먼트를 생성합니다(예:
src/pages/[locale]/index.astro):src/pages/[locale]/index.astro코드 복사코드를 클립보드에 복사
<!-- astro -->---import { getIntlayer } from "intlayer";const { title } = getIntlayer('app');---<h1>{title}</h1>Astro 통합은 개발 중에 언어 인식 라우팅 및 환경 정의를 돕는 Vite 미들웨어를 추가합니다. 또한 직접 로직을 작성하거나
intlayer의getLocalizedUrl과 같은 유틸리티를 사용하여 언어 간 링크를 생성할 수 있습니다.언어 선택기 추가
사용자가 언어를 전환할 수 있도록
LocaleSwitcher컴포넌트를 만들 수 있습니다. 이 컴포넌트는 지원되는 모든 로케일 목록을 표시하고 각 언어로 동일한 페이지에 링크해야 합니다.src/components/LocaleSwitcher.astro코드 복사코드를 클립보드에 복사
---import { locales, getLocaleName, getLocalizedUrl, getLocaleFromPath, getPathWithoutLocale, type LocalesValues,} from "intlayer";const locale = getLocaleFromPath(Astro.url.pathname) as LocalesValues;const pathWithoutLocale = getPathWithoutLocale(Astro.url.pathname);---<nav> { locales.map((localeItem) => ( <a href={getLocalizedUrl(pathWithoutLocale, localeItem)} data-locale={localeItem} aria-current={localeItem === locale ? "page" : undefined} > {getLocaleName(localeItem)} </a> )) }</nav><script> import { setLocaleInStorageClient, getLocalizedUrl, type LocalesValues } from "intlayer"; const localeLinks = document.querySelectorAll("[data-locale]"); localeLinks.forEach((link) => { link.addEventListener("click", (e) => { const locale = link.getAttribute("data-locale") as LocalesValues; // Update the locale cookie setLocaleInStorageClient(locale); }); });</script><style> nav { display: flex; gap: 1rem; } a[aria-current="page"] { font-weight: bold; text-decoration: underline; }</style>지속성에 대한 참고 사항: 클라이언트 측 스크립트에서
setLocaleInStorageClient를 사용하면 사용자의 언어 선호도가 쿠키에 저장됩니다. 이를 통해 Intlayer 미들웨어는 선택을 기억하고 향후 방문 시 사용자가 선호하는 언어로 자동으로 리다이렉트할 수 있습니다.Sitemap 및 Robots.txt
Intlayer는 동적으로 로컬라이즈된 사이트맵과 robots.txt 파일을 생성하기 위한 유틸리티를 제공합니다.
사이트맵
Intlayer는 애플리케이션의 사이트맵을 쉽게 만들 수 있는 내장 사이트맵 생성기를 제공합니다. 로컬라이즈된 경로를 처리하고 검색 엔진에 필요한 메타데이터를 추가합니다.
Intlayer에서 생성한 사이트맵은
xhtml:link네임스페이스(Hreflang XML 확장)를 지원합니다. 원시 URL만 나열하는 기본 사이트맵 생성기와 달리, Intlayer는 페이지의 모든 언어 버전(예:/about,/about?lang=fr,/about?lang=es) 간에 필요한 양항향 링크를 자동으로 생성합니다. 이를 통해 검색 엔진이 올바른 언어 버전을 올바른 사용자에게 색인화하고 제공할 수 있도록 보장합니다.모든 로컬라이즈된 경로를 포함하는 사이트맵을 생성하기 위해
src/pages/sitemap.xml.ts를 생성합니다.src/pages/sitemap.xml.ts코드 복사코드를 클립보드에 복사
import type { APIRoute } from "astro";import { generateSitemap, type SitemapUrlEntry } from "intlayer";const pathList: SitemapUrlEntry[] = [ { path: "/", changefreq: "daily", priority: 1.0 }, { path: "/about", changefreq: "monthly", priority: 0.7 },];const SITE_URL = import.meta.env.SITE ?? "http://localhost:4321";export const GET: APIRoute = async ({ site }) => { const xmlOutput = generateSitemap(pathList, { siteUrl: SITE_URL }); return new Response(xmlOutput, { headers: { "Content-Type": "application/xml" }, });};Robots.txt
검색 엔진 크롤링을 제어하기 위해
src/pages/robots.txt.ts를 생성합니다.src/pages/robots.txt.ts코드 복사코드를 클립보드에 복사
import type { APIRoute } from "astro";import { getMultilingualUrls } from "intlayer";const getAllMultilingualUrls = (urls: string[]) => urls.flatMap((url) => Object.values(getMultilingualUrls(url)) as string[]);const disallowedPaths = getAllMultilingualUrls(["/admin", "/private"]);export const GET: APIRoute = ({ site }) => { const robotsTxt = [ "User-agent: *", "Allow: /", ...disallowedPaths.map((path) => `Disallow: ${path}`), "", `Sitemap: ${new URL("/sitemap.xml", site).href}`, ].join("\n"); return new Response(robotsTxt, { headers: { "Content-Type": "text/plain" }, });};선호하는 프레임워크 계속 사용하기
선호하는 프레임워크를 사용하여 애플리케이션을 계속 빌드하세요.
- Intlayer + React: Intlayer with React
- Intlayer + Vue: Intlayer with Vue
- Intlayer + Svelte: Intlayer with Svelte
- Intlayer + Solid: Intlayer with Solid
- Intlayer + Preact: Intlayer with Preact
TypeScript 설정
Intlayer는 모듈 증강(module augmentation)을 사용하여 TypeScript의 이점을 활용함으로써 코드베이스를 더 견고하게 만듭니다.


TypeScript 설정에 자동 생성된 타입이 포함되어 있는지 확인하세요.
tsconfig.json코드 복사코드를 클립보드에 복사
{ // ... 기존 TypeScript 설정 "include": [ // ... 기존 TypeScript 설정 ".intlayer/**/*.ts", // 자동 생성된 타입 포함 ],}Git 설정
Intlayer가 생성한 파일은 무시하는 것이 좋습니다. 이를 통해 Git 리포지토리에 커밋되는 것을 방지할 수 있습니다.
무시하려면
.gitignore파일에 다음 지침을 추가하세요:bash코드 복사코드를 클립보드에 복사
# Intlayer가 생성한 파일 무시.intlayerVS Code 확장 프로그램
Intlayer 개발 환경을 개선하기 위해 공식 Intlayer VS Code 확장 프로그램을 설치할 수 있습니다.
이 확장 프로그램은 다음 기능을 제공합니다:
- 번역 키 자동 완성.
- 누락된 번역에 대한 실시간 오류 감지.
- 번역된 콘텐츠의 인라인 미리보기.
- 번역을 쉽게 생성하고 업데이트할 수 있는 빠른 작업(Quick Actions).
확장 프로그램 사용에 대한 자세한 내용은 Intlayer VS Code 확장 프로그램 문서를 참조하세요.
컴포넌트에서 콘텐츠 추출(선택 사항)
선택사항기존 코드베이스가 있는 경우 수천 개의 파일을 변환하는 데 시간이 많이 걸릴 수 있습니다.
이 프로세스를 용이하게 하기 위해 Intlayer는 컴포넌트를 변환하고 콘텐츠를 추출하기 위한 컴파일러 / 추출기를 제안합니다.
설정하려면
intlayer.config.ts파일에compiler섹션을 추가할 수 있습니다.intlayer.config.ts코드 복사코드를 클립보드에 복사
import { type IntlayerConfig } from "intlayer";const config: IntlayerConfig = { // ... 나머지 구성 compiler: { /** * 컴파일러 활성화 여부를 나타냅니다. */ enabled: true, /** * 출력 파일 경로를 정의합니다. */ output: ({ fileName, extension }) => `./${fileName}${extension}`, /** * 변환 후 컴포넌트를 저장할지 여부를 나타냅니다. 그렇게 하면 컴파일러를 한 번만 실행하여 앱을 변환한 다음 제거할 수 있습니다. */ saveComponents: false, /** * 사전 키 접두사 */ dictionaryKeyPrefix: "", },};export default config;컴포넌트를 변환하고 콘텐츠를 추출하기 위해 추출기를 실행합니다
bash코드 복사코드를 클립보드에 복사
npx intlayer extract