【编译技术】:Babel——基础的基础

2020-10-26 15:08:57 浏览数 (1)

代码语言:javascript复制
目录
1. Babel 是什么?
2. Babel 能干什么?
3. Babel 核心构成
4. 一个小 Demo

1. Babel 是什么?

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

2. Babel 能干什么?

Babel 能为你做的事情:

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

示例:ES2015 语法转换

示例:JSX 语法转换

示例:TypeScript 语法转换

3. Babel 核心构成

  • @babel/core:The core functionality of Babel resides at the @babel/core module.
    • @babel/cli:Babel comes with a built-in CLI which can be used to compile files from the command line.
    • @babel/plugin-*:Transformations come in the form of plugins, which are small JavaScript programs that instruct Babel on how to carry out transformations to the code.
      • @babel/preset-*:Presets can act as an array of Babel plugins or even a sharable options config.
    • @babel/register:One of the ways you can use Babel is through the require hook. The require hook will bind itself to node's require and automatically compile files on the fly.
    • core-js:Modular standard library for JavaScript. Includes polyfills for ECMAScript up to 2020: promises, symbols, collections, iterators, typed arrays, many other features, ECMAScript proposals, some cross-platform WHATWG / W3C features and proposals like URL. You can load only required features or use it without global namespace pollution.

4. 一个小 Demo

安装依赖:

代码语言:javascript复制
npm install --save-dev @babel/core 
npm install --save-dev @babel/cli 
npm install --save-dev @babel/preset-env
npm install --save-dev @babel/preset-react
npm install --save-dev @babel/preset-typescript

配置Babel(babel.config.json):

代码语言:javascript复制
{
  "presets": [
    "@babel/env",
    "@babel/react",
    "@babel/preset-typescript"
  ]
}

scripts:

代码语言:javascript复制
babel src  --out-dir lib

scripts:

参考:

babel 官网: https://babeljs.io/docs/en/


0 人点赞