작가:
    생성:2024-08-13마지막 업데이트:2025-08-20

    Intlayer 포매터

    개요

    Intlayer는 네이티브 Intl API 위에 구축된 경량 헬퍼 세트와 무거운 포매터를 반복 생성하지 않도록 하는 캐시된 Intl 래퍼를 제공합니다. 이 유틸리티들은 완전한 로케일 인식을 지원하며 메인 intlayer 패키지에서 사용할 수 있습니다.

    캐시된 Intl

    내보내진 Intl은 전역 Intl을 감싼 얇은 캐시 래퍼입니다. 이는 NumberFormat, DateTimeFormat, RelativeTimeFormat, ListFormat, DisplayNames, Collator, PluralRules 인스턴스를 메모이제이션하여 동일한 포매터를 반복 생성하는 것을 방지합니다.

    포매터 생성은 상대적으로 비용이 많이 들기 때문에, 이 캐싱은 동작을 변경하지 않으면서 성능을 향상시킵니다. 이 래퍼는 네이티브 Intl과 동일한 API를 제공하므로 사용법도 동일합니다.

    • 캐싱은 프로세스별로 이루어지며 호출자에게 투명합니다.
    환경에 Intl.DisplayNames가 없으면, 개발자 전용 경고가 한 번 출력됩니다(폴리필 사용을 고려하세요).

    예시:

    ts
    import { Intl } from "intlayer";// 숫자 포맷팅const numberFormat = new Intl.NumberFormat("en-GB", {  style: "currency",  currency: "GBP",});numberFormat.format(1234.5); // "£1,234.50"// 언어, 지역 등의 표시 이름const displayNames = new Intl.DisplayNames("fr", { type: "language" });displayNames.of("en"); // "anglais"// 정렬을 위한 콜레이션const collator = new Intl.Collator("fr", { sensitivity: "base" });collator.compare("é", "e"); // 0 (동일)// 복수형 규칙const pluralRules = new Intl.PluralRules("fr");pluralRules.select(1); // "one"pluralRules.select(2); // "other"

    로케일 유틸리티

    getLocaleLang(locale?)

    로케일 문자열에서 언어 코드를 추출합니다:

    ts
    import { getLocaleLang } from "intlayer";getLocaleLang("en-US"); // "en"getLocaleLang("fr-CA"); // "fr"getLocaleLang("de"); // "de"
    • locale: 언어를 추출할 로케일 (기본값은 현재 로케일)

    getLocaleFromPath(inputUrl)

    URL 또는 경로명에서 로케일 부분을 추출합니다:

    ts
    import { getLocaleFromPath } from "intlayer";getLocaleFromPath("/en/dashboard"); // "en"getLocaleFromPath("/fr/dashboard"); // "fr"getLocaleFromPath("/dashboard"); // "en" (기본 로케일)getLocaleFromPath("https://example.com/es/about"); // "es"
    • inputUrl: 처리할 전체 URL 문자열 또는 경로명
    • returns: 감지된 로케일 또는 로케일이 없을 경우 기본 로케일

    getLocalizedUrl(url, currentLocale, locales?, defaultLocale?, prefixDefault?)

    현재 로케일에 맞는 로컬라이즈된 URL을 생성합니다:

    ts
    import { getLocalizedUrl } from "intlayer";getLocalizedUrl("/about", "fr", ["en", "fr"], "en", false); // "/fr/about"getLocalizedUrl("/about", "en", ["en", "fr"], "en", false); // "/about"getLocalizedUrl("https://example.com/about", "fr", ["en", "fr"], "en", true); // "https://example.com/fr/about"
    • url: 로컬라이즈할 원본 URL
    • currentLocale: 현재 로케일
    • locales: 선택적 지원 로케일 배열 (기본값은 구성된 로케일)
    • defaultLocale: 선택적 기본 로케일 (구성된 기본 로케일을 기본값으로 사용)
    • prefixDefault: 기본 로케일에 접두사를 붙일지 여부 (구성된 값을 기본값으로 사용)

    getHTMLTextDir(locale?)

    로케일에 대한 텍스트 방향을 반환합니다:

    ts
    import { getHTMLTextDir } from "intlayer";getHTMLTextDir("en-US"); // "ltr"getHTMLTextDir("ar"); // "rtl"getHTMLTextDir("he"); // "rtl"
    • locale: 텍스트 방향을 가져올 로케일 (기본값은 현재 로케일)
    • returns: "ltr", "rtl", 또는 "auto"

    콘텐츠 처리 유틸리티

    getContent(node, nodeProps, locale?)

    모든 사용 가능한 플러그인(번역, 열거, 삽입 등)을 사용하여 콘텐츠 노드를 변환합니다:

    ts
    import { getContent } from "intlayer";const content = getContent(  contentNode,  { dictionaryKey: "common", dictionaryPath: "/path/to/dict" },  "fr");
    • node: 변환할 콘텐츠 노드
    • nodeProps: 변환 컨텍스트를 위한 속성
    • locale: 선택적 로케일 (기본값은 구성된 기본 로케일)

    getTranslation(languageContent, locale?, fallback?)

    언어 콘텐츠 객체에서 특정 로케일의 콘텐츠를 추출합니다:

    ts
    import { getTranslation } from "intlayer";const content = getTranslation(  {    en: "Hello",    fr: "Bonjour",    de: "Hallo",  },  "fr",  true); // "Bonjour"
    • languageContent: 로케일을 콘텐츠에 매핑한 객체
    • locale: 대상 로케일 (기본값은 설정된 기본 로케일)
    • fallback: 기본 로케일로 대체할지 여부 (기본값은 true)

    getIntlayer(dictionaryKey, locale?, plugins?)

    키로 사전에서 콘텐츠를 가져오고 변환합니다:

    ts
    import { getIntlayer } from "intlayer";const content = getIntlayer("common", "fr");const nestedContent = getIntlayer("common", "fr", customPlugins);
    • dictionaryKey: 가져올 사전의 키
    • locale: 선택적 로케일 (기본 설정된 기본 로케일 사용)
    • plugins: 선택적 사용자 정의 변환 플러그인 배열

    getIntlayerAsync(dictionaryKey, locale?, plugins?)

    원격 사전에서 비동기적으로 콘텐츠를 가져옵니다:

    ts
    import { getIntlayerAsync } from "intlayer";const content = await getIntlayerAsync("common", "fr");
    • dictionaryKey: 가져올 사전의 키
    • locale: 선택적 로케일 (기본 설정된 기본 로케일 사용)
    • plugins: 선택적 사용자 정의 변환 플러그인 배열

    포매터(Formatters)

    아래의 모든 헬퍼는 intlayer에서 내보내집니다.

    percentage(value, options?)

    숫자를 백분율 문자열로 포맷합니다.

    동작: 1보다 큰 값은 전체 백분율로 해석되어 정규화됩니다 (예: 2525%, 0.2525%).

    • value: number | string
    • options: Intl.NumberFormatOptions & { locale?: LocalesValues }

    예시:

    ts
    import { percentage } from "intlayer";percentage(0.25); // "25%"percentage(25); // "25%"percentage(0.237, { minimumFractionDigits: 1 }); // "23.7%"

    Formatter Functions

    number(value, options?)

    로케일을 인식하는 그룹핑 및 소수점으로 숫자 값을 포맷합니다.

    • value: number | string
    • options: Intl.NumberFormatOptions & { locale?: LocalesValues }
    ts
    number(123456.789); // "123,456.789" (in en-US)number("1000000", { locale: "fr" }); // "1 000 000"number(1234.5, { minimumFractionDigits: 2 }); // "1,234.50"

    percentage(value, options?)

    숫자를 백분율 문자열로 포맷합니다. 1보다 큰 값은 정규화됩니다 (예: 2525%, 0.2525%).

    • value: number | string
    • options: Intl.NumberFormatOptions & { locale?: LocalesValues }
    ts
    percentage(0.25); // "25%"percentage(25); // "25%"percentage(0.237, { minimumFractionDigits: 1 }); // "23.7%"

    currency(value, options?)

    값을 로컬화된 통화로 포맷합니다. 기본값은 USD입니다.

    • value: number | string
    • options: Intl.NumberFormatOptions & { locale?: LocalesValues }
      • Common: currency, currencyDisplay ("symbol" | "code" | "name")
    ts
    currency(1234.5, { currency: "EUR" }); // "€1,234.50"currency("5000", { locale: "fr", currency: "CAD", currencyDisplay: "code" }); // "5 000,00 CAD"

    date(date, optionsOrPreset?)

    날짜/시간 값을 포맷합니다.

    • date: Date | string | number
    • optionsOrPreset: Intl.DateTimeFormatOptions & { locale?: LocalesValues } 또는 preset: "short" | "long" | "dateOnly" | "timeOnly" | "full"
    ts
    date(new Date(), "short"); // 예: "08/02/25, 14:30"date("2025-08-02T14:30:00Z", { locale: "fr", month: "long", day: "numeric" }); // "2 août"

    relativeTime(from, to?, options?)

    두 순간 사이의 상대 시간을 형식화합니다.

    • from: Date | string | number
    • to: Date | string | number (기본값: new Date())
    • options: { locale?, unit?, numeric?, style? }
    ts
    const now = new Date();const in3Days = new Date(now.getTime() + 3 * 864e5);relativeTime(now, in3Days, { unit: "day" }); // "in 3 days"const twoHoursAgo = new Date(now.getTime() - 2 * 3600e3);relativeTime(now, twoHoursAgo, { unit: "hour", numeric: "auto" }); // "2 hours ago"

    units(value, options?)

    단위를 포함하여 숫자 값을 포맷팅합니다.

    • value: number | string
    • options: Intl.NumberFormatOptions & { locale?: LocalesValues }
      • Common: unit (예: "kilometer", "byte"), unitDisplay ("short" | "narrow" | "long")
    ts
    units(5, { unit: "kilometer", unitDisplay: "long", locale: "en-GB" }); // "5 kilometers"units(1024, { unit: "byte", unitDisplay: "narrow" }); // "1,024B"

    compact(value, options?)

    압축 표기법을 사용하여 숫자를 포맷팅합니다.

    • value: number | string
    • options: Intl.NumberFormatOptions & { locale?: LocalesValues }
    ts
    compact(1200); // "1.2K"compact("1000000", { locale: "fr", compactDisplay: "long" }); // "1 million"

    list(values, options?)

    배열을 로컬라이즈된 리스트 문자열로 포맷합니다.

    • values: (string | number)[]
    • options: Intl.ListFormatOptions & { locale?: LocalesValues }
      • 일반적: type ("conjunction" | "disjunction" | "unit"), style ("long" | "short" | "narrow")
    ts
    list(["apple", "banana", "orange"]); // "apple, banana, and orange"list(["red", "green", "blue"], { locale: "fr", type: "disjunction" }); // "rouge, vert ou bleu"

    Cached Intl

    intlayer에서 내보낸 Intl은 전역 Intl을 래핑한 캐시된 래퍼입니다. formatter 인스턴스(NumberFormat, DateTimeFormat 등)를 메모이제이션하여 반복적인 구성을 피하고 성능을 향상시킵니다.

    ts
    import { Intl } from "intlayer";// 숫자 형식 지정const numberFormat = new Intl.NumberFormat("en-GB", {  style: "currency",  currency: "GBP",});numberFormat.format(1234.5); // "£1,234.50"// 언어, 지역 등의 표시 이름const displayNames = new Intl.DisplayNames("fr", { type: "language" });displayNames.of("en"); // "anglais"// 정렬을 위한 대조const collator = new Intl.Collator("fr", { sensitivity: "base" });collator.compare("é", "e"); // 0 (equal)// 복수형 규칙const pluralRules = new Intl.PluralRules("fr");pluralRules.select(1); // "one"pluralRules.select(2); // "other"

    추가 Intl 기능

    Intl.DisplayNames

    언어, 지역, 통화 및 스크립트의 지역화된 이름을 위해:

    ts
    import { Intl } from "intlayer";const languageNames = new Intl.DisplayNames("en", { type: "language" });languageNames.of("fr"); // "French"const regionNames = new Intl.DisplayNames("fr", { type: "region" });regionNames.of("US"); // "États-Unis"

    Intl.Collator

    로케일을 인식한 문자열 비교 및 정렬:

    ts
    import { Intl } from "intlayer";const collator = new Intl.Collator("de", {  sensitivity: "base",  numeric: true,});const words = ["äpfel", "zebra", "100", "20"];words.sort(collator.compare); // ["20", "100", "äpfel", "zebra"]

    Intl.PluralRules

    다양한 로케일에서 복수형을 결정하기 위해:

    ts
    import { Intl } from "intlayer";const pluralRules = new Intl.PluralRules("ar");pluralRules.select(0); // "zero"pluralRules.select(1); // "one"pluralRules.select(2); // "two"pluralRules.select(3); // "few"pluralRules.select(11); // "many"

    Locale Utilities

    units(value, options?)

    Intl.NumberFormatstyle: 'unit'을 사용하여 숫자 값을 현지화된 단위 문자열로 포맷합니다.

    • value: number | string
    • options: Intl.NumberFormatOptions & { locale?: LocalesValues }
      • 공통 필드: unit (예: "kilometer", "byte"), unitDisplay ("short" | "narrow" | "long")
      • 기본값: unit: 'day', unitDisplay: 'short', useGrouping: false

    예제:

    ts
    import { units } from "intlayer";units(5, { unit: "kilometer", unitDisplay: "long", locale: "en-GB" }); // "5 kilometers"units(1024, { unit: "byte", unitDisplay: "narrow" }); // "1,024B" (로케일에 따라 다름)

    getLocaleLang(locale?)

    로케일 문자열에서 언어 코드를 추출합니다:

    ts
    import { getLocaleLang } from "intlayer";getLocaleLang("en-US"); // "en"getLocaleLang("fr-CA"); // "fr"

    compact(value, options?)

    숫자를 축약 표기법(예: 1.2K, 1M)으로 포맷합니다.

    • value: number | string
    • options: Intl.NumberFormatOptions & { locale?: LocalesValues } (notation: 'compact'를 내부적으로 사용)

    예제:

    ts
    import { compact } from "intlayer";compact(1200); // "1.2K"compact("1000000", { locale: "fr", compactDisplay: "long" }); // "1 million"

    getPathWithoutLocale(inputUrl, locales?)

    URL에서 로케일 세그먼트를 제거합니다:

    ts
    import { getPathWithoutLocale } from "intlayer";getPathWithoutLocale("/en/dashboard"); // "/dashboard"getPathWithoutLocale("/fr/dashboard"); // "/dashboard"

    list(values, options?)

    Intl.ListFormat을 사용하여 값 배열을 현지화된 목록 문자열로 포맷합니다.

    • values: (string | number)[]
    • options: Intl.ListFormatOptions & { locale?: LocalesValues }
      • 공통 필드: type ("conjunction" | "disjunction" | "unit"), style ("long" | "short" | "narrow")
      • 기본값: type: 'conjunction', style: 'long'

    예시:

    ts
    import { list } from "intlayer";list(["apple", "banana", "orange"]); // "apple, banana, and orange"list(["red", "green", "blue"], { locale: "fr", type: "disjunction" }); // "rouge, vert ou bleu"list([1, 2, 3], { type: "unit" }); // "1, 2, 3"

    getHTMLTextDir(locale?)

    로케일에 대한 텍스트 방향을 반환합니다:

    ts
    import { getHTMLTextDir } from "intlayer";getHTMLTextDir("en-US"); // "ltr"getHTMLTextDir("ar"); // "rtl"getHTMLTextDir("he"); // "rtl"

    Content Handling Utilities

    React

    클라이언트 컴포넌트:

    tsx
    import {  useNumber,  useCurrency,  useDate,  usePercentage,  useCompact,  useList,  useRelativeTime,  useUnit,} from "react-intlayer/format";// 또는 Next.js 앱에서import {  useNumber,  useCurrency,  useDate,  usePercentage,  useCompact,  useList,  useRelativeTime,  useUnit,} from "next-intlayer/client/format";const MyComponent = () => {  const number = useNumber();  const currency = useCurrency();  const date = useDate();  const percentage = usePercentage();  const compact = useCompact();  const list = useList();  const relativeTime = useRelativeTime();  const unit = useUnit();  return (    <div>      <p>{number(123456.789)}</p>      <p>{currency(1234.5, { currency: "EUR" })}</p>      <p>{date(new Date(), "short")}</p>      <p>{percentage(0.25)}</p>      <p>{compact(1200)}</p>      <p>{list(["apple", "banana", "orange"])}</p>      <p>{relativeTime(new Date(), new Date() + 1000)}</p>      <p>{unit(123456.789, { unit: "kilometer" })}</p>    </div>  );};

    서버 컴포넌트(또는 React 서버 런타임):

    ts
    import {  useNumber,  useCurrency,  useDate,  usePercentage,  useCompact,  useList,  useRelativeTime,  useUnit,} from "intlayer/server/format";// 또는 Next.js 앱에서는import {  useNumber,  useCurrency,  useDate,  usePercentage,  useCompact,  useList,  useRelativeTime,  useUnit,} from "next-intlayer/server/format";
    이 훅들은 IntlayerProvider 또는 IntlayerServerProvider에서 설정된 로케일을 고려합니다.

    getTranslation(languageContent, locale?, fallback?)

    특정 로케일의 콘텐츠를 추출합니다:

    ts
    import { getTranslation } from "intlayer";const content = getTranslation(  { ko: "안녕하세요", en: "Hello", fr: "Bonjour", de: "Hallo" },  "fr",  true); // "Bonjour"

    Vue

    클라이언트 컴포넌트:

    ts
    import {  useNumber,  useCurrency,  useDate,  usePercentage,  useCompact,  useList,  useRelativeTime,  useUnit,} from "vue-intlayer/format";
    이 컴포저블들은 주입된 IntlayerProvider에서 로케일을 고려합니다.

    문서 변경 이력

    버전 날짜 변경 사항
    5.8.0 2025-08-20 vue 포매터 추가
    5.8.0 2025-08-18 포매터 문서 추가

    클라이언트 컴포넌트:

    ts
    import {  useNumber,  useCurrency,  useDate,  usePercentage,  useCompact,  useList,  useRelativeTime,  useUnit,} from "vue-intlayer/format";
    이 컴포저블들은 주입된 IntlayerProvider에서 로케일을 고려합니다.