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

时间:2022-07-28
本文章向大家介绍【编译技术】:Babel——基础的基础,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
目录
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

安装依赖:

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):

{
  "presets": [
    "@babel/env",
    "@babel/react",
    "@babel/preset-typescript"
  ]
}

scripts:

babel src  --out-dir lib

scripts:

参考:

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