1

By default, Babel only converts new JavaScript syntax, such as arrow functions, spread operators, etc. However, new APIs will not be converted, such as global objects such as Set, Maps, Iterator, Generator, Symbol, Reflect, and some methods defined on global objects will not be translated. If you want to use these new objects and methods, you need to provide a polyfill gasket for the current environment.

For example, ES6 has a new Array.from method on the Array object, because this method is a method on the global object, so Babel will not translate this method. If you want this method to work, you must use @babel/polyfill to provide a shim for the current environment.

Install @babel/polyfil

At present, the most commonly used polyfill gasket used with Babel is @babel/polyfil, which is achieved by rewriting the global prototype. It will load the entire polyfil, process the new API in the compiled code, and insert some help in the code. Function, it is more suitable for the project that runs alone.

The installation command is as follows:

 $ npm install --save @babel/polyfil

After installation, we can quote @babel/polyfil at the top of the program entry file::

require('@babel/polyfill')
[].findIndex('babel')

Or use ES6 syntax and use import to import:

import '@babel/polyfill'
[].findIndex('babel')

babel-polyfill solves the problem that Babel does not convert the new API, but directly inserting help functions into the code will pollute the global environment, and different code files contain duplicate codes, resulting in a larger size of the compiled code. While this may be a good thing for applications or command-line tools, it can become a problem if there is already code intended to be released as a library that can be used by others, or if we cannot fully control the environment in which the code runs.

Notice

It should be noted that starting from Babel 7.4.0, the @babel/polyfill package is no longer recommended, but core-js/stable and regenerator-runtime/runtime are used directly, as shown below:

import "core-js/stable";
import "regenerator-runtime/runtime";

Link: https://www.9xkd.com/


知否
221 声望177 粉丝

Skrike while the iron is hot.


« 上一篇
Babel 预设

引用和评论

0 条评论