Babel tutorial: introducing polyfill

The supporting code for this section is the babel02 example from the github repository https://github.com/jruit/babel-tutorial

In general, Babel's main work has two parts:

  • Grammar conversion
  • Fill API

In the previous section, Babel Quick Start, we talked about actually using Babel for syntax conversion, converting ES6 arrow function syntax into ES5 function definition syntax. Arrow function syntax, async function syntax, class definition class syntax and destructuring assignment, etc. are all new ES6 syntax.

What is the complement API? The simple explanation is to add the missing features in the target environment through Polyfill.

We converted var promise = Promise.resolve ('ok') according to the operation in the previous section, and found that the converted code has not changed, the process is as follows.

We create a new babel02 folder, create a new babel configuration file babel.config.js, the content is as follows

  module.exports = {
     presets: ["@babel/env"],
     plugins: []
   }

Create a new main.js file with the following content

  var fn = (num) => num + 2;
  var promise = Promise.resolve('ok')

Then execute the following command to install three npm packages

  // npm一次性安装多个包,包名之间用空格隔开
  npm install --save-dev @babel/cli @babel/core @babel/preset-env

Then execute the command

    npx babel main.js -o compiled.js

The whole process is basically the same as the previous section, except that the code in main.js has an extra line

  var promise = Promise.resolve('ok')

At this time, a new compiled.js will be generated under the folder, the code is as follows:

  "use strict";
  var fn = function fn(num) {
    return num + 2;
  };
  var promise = Promise.resolve('ok');

We observed the compiled.js code generated after the conversion and found that Babel did not convert the ES6 Promise.

We refer to the compiled.js after transcoding through an index.html file. After opening the HTML file in an older browser (such as Firefox 27), the console reports an error: Promise is not defined.

Why didn't Babel convert ES6 Promises?

Because Babel only converts the new JavaScript syntax (syntax) by default, not the new API.

The new API is classified into two categories, one is Promise, Map, Symbol, Proxy, Iterator and other global objects and their own methods, such as Object.assign, Promise.resolve; the other is new instance methods, such as array instances Method [1, 4, -5, 10] .find ((item) => item <0)

If we want ES6's new API to work properly in low-level browsers, we can't just do syntax conversion.

In front-end web projects, the most common approach is to use polyfill to provide a shim for the current environment. The so-called shims refer to things that smooth out the differences between different browsers. Polyfill provides global ES6 objects and implementation of instances by modifying the prototype chain Array.prototype.

Polyfill is a type of file or library that provides unsupported features for the environment in a broad sense. In a narrow sense, it is a polyfill.js file and the @ babel / polyfill npm package.

We can directly import the polyfill.js file in the html file as a global environment gasket. Polyfill.js has Babel's official polyfill.js, as well as third-party ones. We introduce a polyfill script that Babel has already built.

For simplicity, we have introduced polyfill.js in HTML.

  <script src="https://cdn.bootcss.com/babel-polyfill/7.6.0/polyfill.js"></script>

We open the verification in IE9, can also use Firefox27 and other low-level browsers to verify. At this time, it was found that it could run normally.

The way to complete the API is not only through the introduction of polyfill.js file, but also through the entry file of the construction tool (such as webapck), babel configuration file and so on. In this section, the introduction of the polyfill.js file directly into HTML is gradually eliminated in modern front-end projects, and it is rarely used. But this way is simple and straightforward for beginners to understand what polyfill is. We will learn about other ways to complete the API in the following chapters.

summary

This section describes how to fill in the missing APIs of the code runtime environment through the polyfill.js file.

Through the grammatical conversion described in the previous section and the completed API described in this section, you can make a project that uses ES6 to run completely in an environment that does not support the ES6 language.

Note

1. You can download the Firefox 27 of the corresponding operating system on the https://ftp.mozilla.org/pub/firefox/releases/27.0.1/ page, if you use this version for a long time, please set it to not be automatically updated. Settings in Firefox-Options-Advanced-Update.

2. What is an API? Those who are new to programming will be confused when they read the explanations of Baidu Encyclopedia. Let's explain with a simple example: the array in JS has a sort method sort (), this is the API that the JS language setter makes for the array. To extend it, if you use objects, classes, functions or methods that have been written by others, that is using the API.

    What new APIs does ES6 have? Promise objects, Array.from () and Array.of () methods of arrays, flat () and Object.assign () methods of array instances, etc. As long as it is a new object name, class name, function name or method name, it is the new API of ES6.

Blog: Jiang Ruitao's official website
Original link: https://www.jiangruitao.com/docs/babel/rudiments/use-polyfill/
Copyright adopts "Attribution-Non-Commercial Use-Prohibition of Deduction 4.0 International" The license agreement is reproduced and must be noted Original author, link and copyright agreement

Guess you like

Origin www.cnblogs.com/zhansu/p/12724193.html