TypeError:未定义不是构造函数(评估 'new Intl.RelativeTimeFormat('en', { style: 'short', numeric: "auto" })')

hen*_*dry 8 javascript

我有这样的代码:

const rtf = new Intl.RelativeTimeFormat('en', { style: 'short', numeric: "auto" });
Run Code Online (Sandbox Code Playgroud)

在 Safari/605.1.15 中触发错误:

TypeError: undefined is not a constructor (evaluating 'new Intl.RelativeTimeFormat('en', { style: 'short', numeric: "auto" })')
Run Code Online (Sandbox Code Playgroud)

现代 JS 中如何解决 Intl API 可能不存在这一事实?

Gré*_*EUT 7

这种方法没有得到很好的支持。我可以使用相对时间格式吗?

在此输入图像描述

您可以做的是使用一个包来模拟您需要的功能,无论浏览器是什么。

我找到了您可以使用的相对时间格式npm 包。


安装

npm install 相对时间格式 --save

使用

import RelativeTimeFormat from "relative-time-format"
import en from "relative-time-format/locale/en.json"

RelativeTimeFormat.addLocale(en)

// Returns "2 days ago"
new RelativeTimeFormat("en", {
  style: "long" // "long" is the default. Other options: "short", "narrow".
}).format(-2, "day")
Run Code Online (Sandbox Code Playgroud)

检查浏览器是否兼容:

if (Intl === void 0 || typeof Intl.RelativeTimeFormat !== 'function') {
   // Browser not compatible
}
Run Code Online (Sandbox Code Playgroud)

选择 :

const rtf = (Intl &&
            Intl.RelativeTimeFormat &&
            new Intl.RelativeTimeFormat('en', {
               style: 'short',
               numeric: "auto",
            })) || false;

if (!rtf) {
   // Not compatible
}
Run Code Online (Sandbox Code Playgroud)