如果浏览器不支持所需的区域设置,如何将缺少的区域设置添加到 Intl.DateTimeFormat (ES2020)?

问题描述 投票:0回答:2

不幸的是,某些浏览器不支持某些使用 Intl.DateTimeFormat 的区域设置。就我而言,Chrome 中的“kk”语言环境(https://source.chromium.org/chromium/chromium/src/+/master:third_party/icu/scripts/chrome_ui_languages.list)。您可以在控制台中测试您的区域设置:

Intl.DateTimeFormat.supportedLocalesOf('kk')

如果返回空数组[]则表示不支持。

我的问题是如何添加缺少的区域设置?我的意思是可能有一个 Polyfill 可以做到这一点?我正在使用 Vuejs 2

vuejs2 polyfills ecmascript-2020
2个回答
1
投票

终于找到了使用Polyfill的解决方案:

npm i @formatjs/intl-datetimeformat

然后在你的代码中:

import '@formatjs/intl-datetimeformat/polyfill-force’ // Using force to use our polyfill
import '@formatjs/intl-datetimeformat/locale-data/kk’ // Add locales you want
import '@formatjs/intl-datetimeformat/locale-data/ru’ // Add locales you want
import '@formatjs/intl-datetimeformat/add-all-tz' // Add ALL tz data

0
投票

有一个解决方案,仅填充 Intl.DateTimeFormat 中尚未存在的那些区域设置。就我而言,浏览器仅缺少

kk
语言环境。因此我只想用 @formatjs 填充
kk
并通过原始 Intl.DateTimeFormat 使用
en
&
ru

import {
  DateTimeFormat as PolyfillDateTimeFormat,
} from "@formatjs/intl-datetimeformat";

const LOCALES_THAT_ARE_POLYFILLED = ["kk"];

const OriginalDateTimeFormat = Intl.DateTimeFormat;

const DynamicDateTimeFormat = new Proxy(PolyfillDateTimeFormat, {
  construct(target, args) {
    if (LOCALES_THAT_ARE_POLYFILLED.includes(args[0])) {
      return new target(...args);
    } else {
      return OriginalDateTimeFormat(...args);
    }
  },
  get(target, prop) {
    if (prop === "supportedLocalesOf") {
      return (value: string | string[], options?: Pick<Intl.DateTimeFormatOptions, "localeMatcher">) => {
        if (typeof value === "string") {
          if (LOCALES_THAT_ARE_POLYFILLED.includes(value)) {
            return target.supportedLocalesOf(value, options);
          } else {
            return OriginalDateTimeFormat.supportedLocalesOf(value, options);
          }
        } else {
          return value.map((locale) => {
            if (LOCALES_THAT_ARE_POLYFILLED.includes(locale)) {
              return target.supportedLocalesOf(locale, options)[0];
            } else {
              return OriginalDateTimeFormat.supportedLocalesOf(locale, options)[0];
            }
          });
        }
      }
    } else {
      // @ts-ignore
      return target[prop];
    }
  }
});

// also keep in mind to monkey-patch toLocaleString, toLocaleTimeString, toLocaleDateString
Object.defineProperty(Intl, "DateTimeFormat", {
  value: DynamicDateTimeFormat,
  configurable: true,
  enumerable: false,
  writable: true,
});

const _promise = Promise.all([
  import("@formatjs/intl-datetimeformat/locale-data/kk"), // need to be statically defined for bundlers
  import("@formatjs/intl-datetimeformat/add-all-tz"),
]);
© www.soinside.com 2019 - 2024. All rights reserved.