Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Babel #42

Open
conan1992 opened this issue Jul 1, 2020 · 0 comments
Open

Babel #42

conan1992 opened this issue Jul 1, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

Babel

定义:Babel 是一个工具链,主要用于将 ECMAScript 2015+ 版本的代码转换为向后兼容的 JavaScript 语法,以便能够运行在当前和旧版本的浏览器或其他环境中。

Babel做的事:

  • 语法转换
  • 通过 Polyfill 方式在目标环境中添加缺失的特性
  • 源码转换 (codemods)

例如:

// Babel 输入: ES2015 箭头函数
[1, 2, 3].map((n) => n + 1);

// Babel 输出: ES5 语法实现的同等功能
[1, 2, 3].map(function(n) {
  return n + 1;
});

插件

Babel 是一个编译器(输入源码 => 输出编译后的代码)。就像其他编译器一样,编译过程分为三个阶段:解析、转换和打印输出。
如果不对babel不做配置,代码解析之后再输出同样的代码。

  • 转换插件
    例如es2015的arrow-functions;
    查看更多插件

  • 语法插件
    这些插件只允许 Babel 解析(parse) 特定类型的语法(而不是转换);
    注:转换插件会自动启用语法插件。因此,如果你已经使用了相应的转换插件,则不需要指定语法插件。

预设

presets可以理解为是一组插件;
查看更多
例如:@babel/preset-env

参数设置

//plugin

{
  "plugins": ["pluginA", ["pluginA"], ["pluginA", {}]]
}
//传递一个以参数名作为键(key)的对象。
{
  "plugins": [
    [
      "transform-async-to-module-method",
      {
        "module": "bluebird",
        "method": "coroutine"
      }
    ]
  ]
}
//presets
{
  "presets": [
    "presetA",
    ["presetA"],
    ["presetA", {}],
  ]
}
{
  "presets": [
    ["@babel/preset-env", {
      "loose": true,
      "modules": false
    }]
  ]
}

插件、预设顺序

  • 插件在 Presets 前运行。
  • 插件顺序从前往后排列。
  • Preset 顺序是颠倒的(从后往前)。
{
  "plugins": ["transform-decorators-legacy", "transform-class-properties"]
}
//先执行 transform-decorators-legacy ,在执行 transform-class-properties。

{
  "presets": ["es2015", "react", "stage-2"]
}
//将按如下顺序执行:stage-2、react 然后是 es2015

polyfill

Polyfill是对执行环境或者其它功能的一个补充.
比如我们想在edge17里使用includes方法,但是实际上此浏览器环境是不支持这个方法的,所以就让polyfill帮我们实现,给我们提供includes可以运行的环境,看如下代码:

// 原来的代码
var hasTwo = [1, 2, 3].includes(2);

// 加了polyfill之后的代码
require("core-js/modules/es7.array.includes");
require("core-js/modules/es6.string.includes");
var hasTwo = [1, 2, 3].includes(2);
  • 使用
cnpm i --save @babel/polyfill

//babel.config.js添加
useBuiltIns: "usage"

使用

npm install --save-dev @babel/core @babel/cli @babel/preset-env
npm install --save @babel/polyfill

//配置文件babel.config.js
{
  "presets": [
    [
      "@babel/env",
      {
        "targets": {
          "edge": "17",
          "firefox": "60",
          "chrome": "67",
          "safari": "11.1",
        },
        "useBuiltIns": "usage",
      }
    ]
  ]
}

npx babel src --dir lib

###参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant