半月前,我使用@vue/cli 3.x版本搭建项目,引入一个包后,然后编译卡住不动,报这个错,因为当时刚好练习嵌套路由,以为是啥 modulerouter模块起冲突,按它提示安装了core-js@3,编译还是报错,卸了该版本,又装了core-js@2,编译还是有这个警告提示! 然后我直接把代码回退一个版本,提示依旧,编译后代码能正常正常跑起来,就没管他了。
这几天我在学习webpack4.x,跟着前辈们的代码,边看边敲。在引入@babel/preset-env一个帮你配置babel的preset,根据配置的目标环境自动采用需要的babel插件)配置babel中的useBuiltIns: 'usage'时,编译出现又出现这个警告提示,这次又撞上我了,遂决定盘它!英文不咋好,直接谷歌翻译了一下下文!

WARNING: We noticed you're using the `useBuiltIns` option without declaring a core-js version. Currently, we assume version 2.x when no version is passed. Since this default
version will likely change in future versions of Babel, we recommend explicitly setting the core-js version you are using via the `corejs` option.

You should also be sure that the version you pass to the `corejs` option matches the version specified in your `package.json`'s `dependencies` section. If it doesn't, you need to run one of the following commands:

  npm install --save core-js@2    npm install --save core-js@3
  yarn add core-js@2              yarn add core-js@3

大致意思是让我要么在package.json中的dependencies中加入了"core-js"的某个版本,要么安装"core-js"(安装是不可能再安装的!)
按照提示我在@vue/cli 3.x项目的package.jsondependencies中加入了"core-js": "^2.6.5",然后编译成功,没有了那个警告提示!

关于Babel7.4.0官网对于配置@babel/preset-envuseBuiltIns的介绍
useBuiltIns
“usage” | “entry” | false, defaults to false.

This option adds direct references to the core-js module as bare imports. Thus core-js will be resolved relative to the file itself and needs to be accessible. You may need to specify core-js@2 as a top level dependency in your application if there isn’t a core-js dependency or there are multiple versions.

useBuiltIns: 'usage' (experimental)

Adds specific imports for polyfills when they are used in each file. We take advantage of the fact that a bundler will load the same polyfill only once.

注意:experimental(实验的),我似乎明白了啥

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "useBuiltIns": "usage"
      }
    ]
  ],
  "plugins": ["@babel/plugin-transform-runtime"]
}

.babelrc配置了"useBuiltIns": "usage"后,Babel 会在你使用到 ES2015+ 新特性时,自动添加 babel-polyfill 的引用,并且是 partial 级别的引用。按我的理解按需引入。。。

请注意: usage 的行为类似 babel-transform-runtime,不会造成全局污染,因此也会不会对类似 Array.prototype.includes() 进行 polyfill。

项目如果是用 babel7 来转译,需要安装 @babel/core、@babel/preset-env 和 @babel/plugin-transform-runtime,而不是 babel-core、babel-preset-env 和 babel-plugin-transform-runtime,它们是用于 babel6 的

Logo

前往低代码交流专区

更多推荐