Typescript 目标 &在旧版浏览器上使用 Promise.allSettled 的库配置
我使用的是打字稿版本 4.3.5 和节点版本 14.18.1。我正在编译针对旧版和新版浏览器的代码(tsconfig 中的 target=es5
)。我在源代码中使用 Promise.all 和 Promise.allSettled 。
在较旧的浏览器上,特别是 iPhone 8、IOS 版本 11 上的 Safari,我收到 Promise.allSettled 客户端错误。
根据我的理解,当使用 target=es5
时,打字稿应该编译以使代码与旧设备兼容,因此 Promise.allSettled 应该可以工作。请帮我理解这个问题!以下是我的 tsconfig.json
{
"compilerOptions": {
"sourceMap": true,
"target": "es5",
"module": "commonjs",
"esModuleInterop": true,
"outDir": "dist",
"jsx": "react",
"lib": [
"ES2020.Promise",
"dom",
"webworker"
],
"skipLibCheck": true
},
"include": [
"typings/node.d.ts",
"typings/modules.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules",
"**/*.scss.d.ts"
]
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如问题为什么我需要使用 Typescript 进行填充?,TypeScript 不会自动提供向后兼容性实现 (“polyfills”)。因此,
target
tsconfig 的作用比您想象的要少:它仅像箭头函数和生成器一样重写语法,而不是像 Promise 那样重写库。事实上,您首先可以解析 Promise.allSettled 的唯一原因是您在 "ES2020.Promise"。 org/tsconfig#lib" rel="nofollow noreferrer">lib
列表,它告诉 TypeScript 在您的环境中您可以假设您有权访问 ES2020 Promises (具体来说Promise.allSettled
< /a>)。从那些
lib
文档 中,强调我的:问题Promise.all 已在 babel ES6 实现中解决,你有多种选择来自己提供一个 polyfill,但值得注意的是 es.promise.all-settled.js 在 core-js 。您可以使用
polyfills
条目将它们集成到您的 Webpack 构建中点指向一个短的polyfill-import-only JS文件,尽管使用babel-polyfill
的建议是已弃用,取而代之的是core-js/stable
。您需要
导入
或需要
其中之一:core-js/stable/promise/all-settled
promise.allsettled
ts-polyfill/lib/es2020-promise
(无论如何使用core-js
)As in the question Why do I need a polyfill with Typescript?, TypeScript doesn't automatically provide backwards-compatibility implementations ("polyfills"). Consequently, the
target
tsconfig does less than you think it would: It only rewrites syntax like arrow functions and generators, not libraries like Promise. In fact, the only reason you can resolve Promise.allSettled in the first place is that you've specifically listed"ES2020.Promise"
in yourlib
list, which tells TypeScript that in your environment you can assume you have access to ES2020 Promises (specificallyPromise.allSettled
).From those
lib
docs, emphasis mine:As in the question Promise.allSettled in babel ES6 implementation, you have several options to provide a polyfill yourself, but a notable one is es.promise.all-settled.js in core-js. You can integrate those into your Webpack build using the
polyfills
entry point pointing to a short polyfill-import-only JS file, though the suggestion to usebabel-polyfill
has been deprecated in favor ofcore-js/stable
.You would need to
import
orrequire
one of these:core-js/stable/promise/all-settled
promise.allsettled
ts-polyfill/lib/es2020-promise
(usescore-js
anyway)