작가:
    생성: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가 없으면, 개발자 전용 경고가 한 번 출력됩니다(폴리필 사용을 고려하세요).

    로케일 유틸리티

    getLocaleLang(locale?)

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

    getLocaleFromPath(inputUrl)

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

    • inputUrl: 처리할 전체 URL 문자열 또는 경로명
    • returns: 감지된 로케일 또는 로케일이 없을 경우 기본 로케일

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

    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"
    

    getHTMLTextDir(locale?)

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

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

    콘텐츠 처리 유틸리티

    getContent(node, nodeProps, locale?)

    ts
    import { getContent } from "intlayer";
    
    const content = getContent(
      contentNode,
      { dictionaryKey: "common", dictionaryPath: "/path/to/dict" },
      "fr"
    );
    

    getTranslation(languageContent, locale?, fallback?)

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

    • languageContent: 로케일을 콘텐츠에 매핑한 객체
    • locale: 대상 로케일 (기본값은 설정된 기본 로케일)
    • fallback: 기본 로케일로 대체할지 여부 (기본값은 true)

    getIntlayer(dictionaryKey, locale?, plugins?)

    ts
    import { getIntlayer } from "intlayer";
    
    const content = getIntlayer("common", "fr");
    const nestedContent = getIntlayer("common", "fr", customPlugins);
    

    getIntlayerAsync(dictionaryKey, locale?, plugins?)

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

    ts
    import { getIntlayerAsync } from "intlayer";
    
    const content = await getIntlayerAsync("common", "fr");
    

    포매터(Formatters)

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

    percentage(value, options?)

    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?)

    예제:

    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?)

    예제:

    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?)

    예시:

    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

    클라이언트 컴포넌트:

    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";
    

    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에서 로케일을 고려합니다.