포매터가 실제로 사용하는 로케일과 옵션을 확인하는 방법은 무엇인가요?
resolvedOptions() 메서드를 사용하여 Intl 포매터의 실제 구성을 검사하세요
소개
JavaScript에서 Intl 포매터를 생성할 때 요청한 옵션이 항상 받는 옵션과 같지는 않습니다. 브라우저는 로케일 협상을 수행하고 기본값을 채우며 설정을 정규화하여 최종 구성을 생성합니다. resolvedOptions() 메서드를 사용하면 포매터가 실제로 사용하고 있는 것을 정확히 확인할 수 있습니다.
Intl API의 모든 포매터에는 resolvedOptions() 메서드가 있습니다. 여기에는 Intl.DateTimeFormat, Intl.NumberFormat, Intl.ListFormat, Intl.PluralRules, Intl.Collator 등이 포함됩니다. 이 메서드는 입력을 처리한 후 포매터가 최종적으로 사용하게 된 모든 구성 세부 정보를 포함하는 객체를 반환합니다.
이 메서드는 주로 디버깅, 브라우저 동작 이해, 현재 환경에서 사용 가능한 기능 감지에 유용합니다.
기본 구문
resolvedOptions() 메서드는 매개변수를 받지 않습니다. 모든 포매터 인스턴스에서 호출하면 객체를 반환합니다.
const formatter = new Intl.DateTimeFormat('en-US');
const options = formatter.resolvedOptions();
console.log(options);
// {
// locale: 'en-US',
// calendar: 'gregory',
// numberingSystem: 'latn',
// timeZone: 'America/Los_Angeles',
// ...
// }
반환된 객체에는 날짜 포매터의 경우 최소한 locale, calendar, numberingSystem 속성이 항상 포함되며, 숫자 포매터의 경우 locale와 numberingSystem가 포함됩니다. 추가 속성은 지정한 옵션과 포매터 유형이 지원하는 것에 따라 달라집니다.
요청한 옵션이 해석된 옵션과 다른 이유
요청한 옵션이 해석된 옵션과 다를 수 있는 주요 이유는 세 가지입니다.
첫째, 로케일 협상은 정확한 요청이 지원되지 않을 때 사용 가능한 최적의 로케일을 찾습니다. de-AT를 요청했지만 브라우저에 de만 있는 경우 해결된 로케일은 de가 됩니다.
const formatter = new Intl.DateTimeFormat('de-AT-u-ca-buddhist');
const options = formatter.resolvedOptions();
console.log(options.locale);
// Likely outputs: 'de-AT' or 'de'
console.log(options.calendar);
// Likely outputs: 'gregory' (if Buddhist calendar is not supported)
둘째, 브라우저는 지정하지 않은 옵션에 대해 기본값을 채웁니다. 이러한 기본값은 로케일별로 다릅니다.
const formatter = new Intl.NumberFormat('en-US');
const options = formatter.resolvedOptions();
console.log(options.style);
// Outputs: 'decimal'
console.log(options.minimumFractionDigits);
// Outputs: 0
console.log(options.maximumFractionDigits);
// Outputs: 3
셋째, 브라우저는 특정 옵션을 정규 형식으로 정규화합니다. dateStyle 또는 timeStyle를 사용하는 경우 브라우저는 해결된 옵션에 이를 포함하지 않습니다. 대신 이들이 확장되는 개별 구성 요소 옵션을 포함합니다.
실제 사용 중인 로케일 확인
resolved options의 locale 속성은 포매터가 사용하고 있는 정확한 로케일을 알려줍니다. 이는 로케일 협상의 결과입니다.
const formatter = new Intl.DateTimeFormat(['zh-TW', 'zh-CN', 'en-US']);
const options = formatter.resolvedOptions();
console.log(options.locale);
// Outputs the first supported locale from the list
유니코드 확장 키워드를 포함하는 로케일을 요청하는 경우, 해당 키워드가 지원되지 않거나 별도의 옵션으로 적용된 경우 해석된 로케일에 해당 키워드가 포함되지 않을 수 있습니다.
const formatter = new Intl.NumberFormat('en-US-u-nu-arab');
const options = formatter.resolvedOptions();
console.log(options.locale);
// Might output: 'en-US'
console.log(options.numberingSystem);
// Might output: 'arab' or 'latn' depending on support
날짜 및 시간 형식 옵션 검사
Intl.DateTimeFormat의 경우, resolved options에는 표시될 날짜 및 시간 구성 요소와 표시 방법에 대한 세부 정보가 포함됩니다.
const formatter = new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
timeZone: 'America/New_York'
});
const options = formatter.resolvedOptions();
console.log(options.year);
// Outputs: 'numeric'
console.log(options.month);
// Outputs: 'long'
console.log(options.day);
// Outputs: 'numeric'
console.log(options.timeZone);
// Outputs: 'America/New_York'
console.log(options.calendar);
// Outputs: 'gregory'
dateStyle 또는 timeStyle를 사용하면 이러한 단축 표현은 resolved options에 포함되지 않습니다. 브라우저는 로케일을 기반으로 개별 구성 요소 옵션으로 확장합니다.
const formatter = new Intl.DateTimeFormat('en-US', {
dateStyle: 'full'
});
const options = formatter.resolvedOptions();
console.log(options.dateStyle);
// Outputs: undefined
console.log(options.weekday);
// Outputs: 'long'
console.log(options.year);
// Outputs: 'numeric'
console.log(options.month);
// Outputs: 'long'
console.log(options.day);
// Outputs: 'numeric'
옵션 없이 날짜 포매터를 생성하는 경우, 해석된 옵션은 브라우저가 해당 로케일에 대해 기본값으로 선택한 내용을 보여줍니다.
const formatter = new Intl.DateTimeFormat('ja-JP');
const options = formatter.resolvedOptions();
console.log(options);
// Shows default date component options for Japanese locale
숫자 형식 옵션 검사
Intl.NumberFormat의 경우, resolved options는 스타일, 정밀도, 그룹화 및 기타 포맷 세부 정보를 알려줍니다.
const formatter = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});
const options = formatter.resolvedOptions();
console.log(options.style);
// Outputs: 'currency'
console.log(options.currency);
// Outputs: 'USD'
console.log(options.currencyDisplay);
// Outputs: 'symbol'
console.log(options.minimumFractionDigits);
// Outputs: 2
console.log(options.maximumFractionDigits);
// Outputs: 2
통화만 지정했지만 브라우저가 currencyDisplay 및 소수 자릿수에 대한 기본값을 채운 것을 확인할 수 있습니다.
반올림 옵션을 사용하는 경우, 해석된 옵션은 숫자가 정확히 어떻게 반올림될지 보여줍니다.
const formatter = new Intl.NumberFormat('en-US', {
minimumSignificantDigits: 3,
maximumSignificantDigits: 5
});
const options = formatter.resolvedOptions();
console.log(options.minimumSignificantDigits);
// Outputs: 3
console.log(options.maximumSignificantDigits);
// Outputs: 5
다른 포매터 타입 검사하기
resolvedOptions() 메서드는 모든 Intl 포매터에서 동일한 방식으로 작동합니다.
Intl.ListFormat의 경우 타입과 스타일을 표시합니다.
const formatter = new Intl.ListFormat('en-US', {
style: 'long',
type: 'conjunction'
});
const options = formatter.resolvedOptions();
console.log(options.locale);
// Outputs: 'en-US'
console.log(options.style);
// Outputs: 'long'
console.log(options.type);
// Outputs: 'conjunction'
Intl.PluralRules의 경우 타입과 최소/최대 자릿수를 표시합니다.
const formatter = new Intl.PluralRules('en-US', {
type: 'ordinal'
});
const options = formatter.resolvedOptions();
console.log(options.locale);
// Outputs: 'en-US'
console.log(options.type);
// Outputs: 'ordinal'
console.log(options.minimumIntegerDigits);
// Outputs: 1
resolvedOptions()의 일반적인 사용 사례
가장 일반적인 사용 사례는 디버깅입니다. 포맷된 출력이 예상과 다르게 보일 때 resolvedOptions()는 포매터가 실제로 수행하고 있는 작업을 이해하는 데 도움이 됩니다.
const formatter = new Intl.DateTimeFormat('en-US', {
dateStyle: 'medium'
});
console.log(formatter.format(new Date()));
// Check the output
console.log(formatter.resolvedOptions());
// See exactly which options produced that output
또 다른 사용 사례는 기능 감지입니다. 특정 달력, 숫자 체계 또는 기타 기능이 지원되는지 요청하고 실제로 무엇이 해석되었는지 확인할 수 있습니다.
const formatter = new Intl.DateTimeFormat('en-US', {
calendar: 'islamic'
});
const options = formatter.resolvedOptions();
if (options.calendar === 'islamic') {
console.log('Islamic calendar is supported');
} else {
console.log('Islamic calendar is not supported, using ' + options.calendar);
}
resolvedOptions()를 사용하여 사용자의 로케일 기본 설정을 가져올 수도 있습니다. 로케일 인수 없이 포매터를 생성하면 브라우저는 사용자의 기본 설정을 사용합니다.
const formatter = new Intl.DateTimeFormat();
const options = formatter.resolvedOptions();
console.log(options.locale);
// Outputs: the user's preferred locale
console.log(options.timeZone);
// Outputs: the user's time zone
console.log(options.hourCycle);
// Outputs: the user's hour cycle preference (12 or 24 hour)
마지막으로 해석된 옵션을 사용하여 동일한 포매터를 재생성할 수 있습니다. 반환된 객체는 생성자에 다시 전달될 수 있습니다.
const formatter1 = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD'
});
const options = formatter1.resolvedOptions();
const formatter2 = new Intl.NumberFormat(options.locale, options);
// formatter2 will format numbers identically to formatter1
핵심 요점
resolvedOptions() 메서드는 포매터가 사용하고 있는 실제 구성을 포함하는 객체를 반환합니다. 이 구성은 로케일 협상, 기본값 및 정규화로 인해 요청한 내용과 다를 수 있습니다.
모든 Intl 포매터에는 이 메서드가 있습니다. 매개변수 없이 호출하면 locale, calendar, numberingSystem와 같은 속성 및 포매터별 옵션이 포함된 객체를 받습니다.
resolvedOptions()는 주로 포매터 동작 디버깅, 사용 가능한 기능 감지, 브라우저가 옵션을 해석한 방식 이해를 위해 사용합니다. 반환된 객체는 동일한 포매터를 재생성하거나 사용자 기본 설정을 검사하는 데에도 사용할 수 있습니다.