[英]How do I polyfill Promise.any() using babel 7?
我使用 webpack 為我的客戶捆綁我的代碼。 According to my question here Is it possible to break away from await Promise.all when any promise has fulfilled (Chrome 80) I want to use Promise.any()
but Promise.any
is only available for Chrome85+ and my clients need me to support鉻 80+。 自然地,我曾想過使用 babel 可以Promise.any()
,例如 corejs 提供Promise.any 。 但我不知道我做錯了什么,現在使用 Babel 7 polyfill 我什至無法讓 Promise.any 為 Chrome85+ 工作!
以下是我所做的,
首先,我的 webpack.config.js
module.exports = {
entry: {
index: './src/index.js'
ui:'./src/ui/index.js'
},
output: {
path: path.resolve(__dirname, './dist'),
filename: '[name].js',
libraryTarget: 'umd',
libraryExport: 'default',
umdNamedDefine: true,
library: '[name]'
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader'
}
},
...
}
我最初使用 Babel 6。使用 Babel 6,我可以驗證 webpack 捆綁的代碼(使用 Promise.any)適用於 Chrome 85+(可能它沒有在 all520.
然后我將 Babel 6 升級到 Babel 7,使用npx babel-upgrade --write
和一些曲折(例如"useBuiltIns": 'usage'
)。 webpack 可以捆綁我的代碼,但令我驚訝的是,與Promise.any()
捆綁的代碼甚至無法在 Chrome85+ 上運行。 我收到錯誤消息“未捕獲(承諾)被拒絕”
以下是我的babelrc
{
"env": {
"production": {
"presets": [
[
"@babel/preset-env",
{
"targets": {
"browsers": [
"last 4 Chrome versions",
"last 3 Firefox versions",
]
},
"modules": "commonjs",
"debug": true,
"useBuiltIns": 'usage'
}
]
],
"plugins": [
[
"@babel/plugin-transform-runtime",
{
"corejs": 2,
"regenerator": true
}
]
]
}
}
}
我做錯了什么?
我打開了一個針對 core-js 的問題,作者告訴我我不應該使用 core-js@2。 有了那個指針,我終於使它與 core-js@3 一起工作了!
以下是我的.babelrc
。 要點是在“ presets ”或“@babel/plugin-transform-runtime”中設置 corejs3,但不能同時設置。 讓 babel 工作非常困難,我在這里列出了 my.babelrc,但我不確定我是否已經正確設置了所有內容。
"production": {
"presets": [
[
"@babel/preset-env",
{
"targets": { ... },
"modules": "commonjs",
"useBuiltIns": "usage",
"corejs": {
"version": 3,
"proposals": true
}
}
]
],
"plugins": [
[
"@babel/plugin-transform-runtime",
{
"regenerator": true
//or don't useBuiltIns but here
// "corejs": {
// "version": 3,
// "proposals": true
// }
}
]
]
}
有了這個設置,我可以看到 webpack output 和 polyfill 終於可以工作了!
Added following core-js polyfills:
esnext.aggregate-error { "chrome":"78", "ie":"10", "safari":"13.1" }
esnext.promise.any { "chrome":"78", "ie":"10", "safari":"13.1" }
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.