【问题标题】:Configure `@babel/runtime-corejs3` to exclude es.date.now配置 `@babel/runtime-corejs3` 排除 es.date.now
【发布时间】:2020-04-03 21:34:10
【问题描述】:

我试图阻止@babel/preset-env + @babel/plugin-transform-runtime + @babel/runtime-corejs3 替换Date.now(),以便解决an issue preventing @sinonjs/fake-timers from working correctly

根据documentation for core-js,应该有办法阻止它应用es.date.now polyfill,但我不知道如何应用这个配置。

示例

index.js

import FakeTimers from '@sinonjs/fake-timers'

FakeTimers.install()

console.log(new Date().getTime())
console.log(Date.now())

巴别塔转译

$(npm bin)/babel index.js
...
console.log(new Date().getTime());
console.log((0, _now["default"])());

注意traspilation 输出的最后一行——我希望它是console.log(Date.now());

在查看 @babel/preset-env 的文档后,我觉得 the exclude option 是我正在寻找的东西,但我无法让它工作:

module.exports = {
  presets: [
    ['@babel/preset-env', { exclude: ['es.date.now'] }]
  ],
  plugins: [
    ['@babel/plugin-transform-runtime', { corejs: 3 }]
  ]
}

上面给了我一个错误:

> $(npm bin)/babel index.js
{ Invariant Violation: [BABEL] ./index.js: Invalid Option: The plugins/built-ins 'es.date.now' passed to the 'exclude' option are not
    valid. Please check data/[plugin-features|built-in-features].js in babel-preset-env (While processing: "./node_modules/@babel/preset-env/lib/index.js")
...

如何配置 Babel 以在 traspilation 期间排除 es.date.now polyfill?


项目文件

package.json

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.8.4",
    "@babel/core": "^7.9.0",
    "@babel/plugin-transform-runtime": "^7.9.0",
    "@babel/preset-env": "^7.9.0",
    "@babel/register": "^7.9.0"
  },
  "dependencies": {
    "@babel/runtime": "^7.9.2",
    "@babel/runtime-corejs3": "^7.9.2",
    "@sinonjs/fake-timers": "^6.0.1"
  }
}

babel.config.js

module.exports = {
  presets: ['@babel/preset-env'],
  plugins: [
    ['@babel/plugin-transform-runtime', { corejs: 3 }]
  ]
}

【问题讨论】:

  • 当然,您可以通过混淆愚蠢的查找替换算法来解决这个问题:``` +const dateObj = Date; + console.log(新日期().getTime()); -console.log(日期。现在()); +console.log(dateObj.now()); ```
  • 我遇到了同样的问题,发现如果不使用 plugin-transform-runtime,那么它可以工作。似乎是运行时插件的错误

标签: javascript babeljs sinon core-js


【解决方案1】:

https://github.com/babel/babel/issues/10008。 plugin-transform-runtime 不支持浏览器目标。 plugin-transform-runtime 和 preset-env 可以独立工作。

所以,总结一下。目前不支持

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-07
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-23
    • 2020-10-09
    相关资源
    最近更新 更多