1. babel是什么

Babel 是一个 JavaScript 编译器

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

  • 语法转换
  • 通过 Polyfill 方式在目标环境中添加缺失的特性 (通过引入第三方 polyfill 模块,例如 core-js)
  • 源码转换(codemods)
    例如:

    // Babel 输入: ES2015 箭头函数
    [1, 2, 3].map(n => n + 1);
    
    // Babel 输出: ES5 语法实现的同等功能
    [1, 2, 3].map(function(n) {
      return n + 1;
    });
    
支持最新语法,而无需等待浏览器的支持

例如:Class and Property Decorators (Stage 1)

@frozen class Foo {
  @configurable(false) @enumerable(true) method() {}
}
function frozen(constructor, parent, elements) {
  return {
	constructor,
	elements,
	finisher(constructor) {
	  Object.freeze(constructor.prototype)
	  Object.freeze(constructor)
	}
  }
}
function configurable(configurable) {
  return decorator;
  function decorator(previousDescriptor) {
	return {
	  ...previousDescriptor,
	  descriptor: {
		...previousDescriptor.descriptor,
		configurable
	  }
	}
  }
}
function enumerable(enumerable) {
  return decorator;
  function decorator(previousDescriptor) {
	return {
	  ...previousDescriptor,
	  descriptor: {
		...previousDescriptor.descriptor,
		enumerable
	  }
	}
  }
}

2. 配置

  • babel.config.json (官方推荐格式)

    {
    	"presets": [],
    	"plugins": []
    }
    
  • .babelrc.json

    {
    	"presets": [],
    	"plugins": []
    }
    
  • babel.config.js

    module.exports = {
    	"presets": [],
    	"plugins": []
    }
    

3. 预设(presets)

  • @babel/preset-env

    • @babel/preset-env is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller!(@babel/preset env是一个智能预设,允许您使用最新的JavaScript,而无需微观管理目标环境需要哪些语法转换(以及可选的浏览器多边形填充)。这既让您的生活更轻松,也让JavaScript包更小!)
    • 安装pnpm add @babel/preset-env -D
    • 基本配置参数:
      • targets: 编译目标版本,默认为{}
      • modules: 是否启用 ES 模块语法到其他模块类型的转换,默认是auto
      • include: 需要编译的目录,默认是[],例如['plugin/keys.js',/node_modules\/myPlugins/]
      • exclude: 编译排除项目,默认是[]
      • useBuiltIns: 按需加载 默认是entry
      • corejs: 需要使用的corejs版本
  • @babel/preset-typescript

    • 如果使用ts,则建议使用此预设
    • 安装pnpm add @babel/preset-typescript
    • 基本配置参数
      • isTSX:开启 jsx 解析,默认为false
      • jsxPragma: 替换编译 JSX 表达式时所使用的函数,默认是React
      • jsxPragmaFrag:替换编译 JSX 片段表达式时使用的函数,默认是React.Fragment
      • allExtensions: 默认是false
  • 其它预设请查看babel官网介绍Babel

3. 插件(plugins)

  1. 初始化项目

    • npm init -y
  2. 安装依赖

    • pnpm add @babel/cli @babel/core @babel/plugin-transform-runtime @babel/preset-env @babel/preset-typescript @babel/runtime-corejs3 core-js -D
      或者
    • npm install @babel/cli @babel/core @babel/plugin-transform-runtime @babel/preset-env @babel/preset-typescript @babel/runtime-corejs3 core-js -D
      或者
    • yarn add @babel/cli @babel/core @babel/plugin-transform-runtime @babel/preset-env @babel/preset-typescript @babel/runtime-corejs3 core-js -D
  3. package.json同级目录新建配置文件babel.config.js,并新增如下内容

    module.exports = {
    	presets: [
    		[
    			// babel预设
    			'@babel/preset-env',
    			{
    				// 使用corejs 3的版本
    				corejs: 3,
    				// 按需加载
    				useBuiltIns: 'usage',
    				// 不使用模块化  交给其它打包工具处理
    				modules: false
    			}
    		],
    		[
    			// typescript,
    			'@babel/preset-typescript',
    			{
    				isTSX: true,
    				allExtensions: true
    			}
    		]
    	],
    	plugins: [
    		[
    			// 只引入用到的模块
    			'@babel/plugin-transform-runtime',
    			{
    				corejs: 3,
    				helpers: true,
    				regenerator: true,
    				useESModules: false
    			}
    		]
    	]
    };
    
  4. package.json同级目录新建文件夹source存放源代码文件。

  • main.ts
    // Person类
    class Person {
    	name: string;
    	age: number;
    	constructor(name: string, age: number) {
    		this.name = name;
    		this.age = age;
    	}
    }
    // 实例化一个Person类
    let p = new Person('张三', 18);
    console.log(p.name);
    console.log(p.age);
    
    // 两数相加
    const add = (a: number, b: number): number => {
    	return a + b;
    };
    
    // Map类型
    const map = new Map([]);
    
    // Set类型
    const set = new Set([]);
    
  1. 新增script脚本命令

    "scripts": {
    	"build": "babel source/* --out-file lib/main.js"
    },
    
  2. 执行npm run build
    lib/main.js
    image