分享
Babel 入门系列

Babel 入门系列一

文档说明

  • 以下教程只针对 babel7.X
  • 直接看文档可能很懵逼, 先来点示例入门体验下babel的魅力

Babel 是什么 能解决什么?

官方文档 (opens in a new tab) 官方演示 (opens in a new tab)

  • Babel 是一个工具链,主要用于将 ECMAScript 2015+ 代码转换为当前和旧版浏览器或环境中向后兼容的 JavaScript 版本。
  1. 转换语法
  2. 对目标环境添加缺少的 Polyfill (babel7.x 统一使用 core-js) (Polyfill(垫片) 对于新的API在浏览器不支持时,由Polyfill实现)

node 示例

  1. 创建项目
mkdir /node-babel-test
cd /node-babel-test
yarn init -y
yarn add @babel/cli @babel/core @babel/preset-env core-js @babel/plugin-proposal-function-bind -D
  1. 编写babel编译命令
 # 在 package.json 中添加以下代码  (别把注释加上去了)
 # npx babel 相当于 ./node_modules/.bin/babel  src 表示源文件   lib 表示编译后文件
 "scripts": {
    "dev": "npx babel src --out-dir lib"
  },
  1. 创建 babel.config.js 配置文件 (babel配置文件方式支持多种 文档 (opens in a new tab))
// 当前配置就是 ES-NEXT 语法转换 node 对应版本语法
module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          node: 16,
        },
        useBuiltIns: 'usage',
        corejs: "3.25.5",
      }
    ]
  ],
  plugins: ['@babel/plugin-proposal-function-bind']
}
  1. 编写测试文件
class Src {
  static s = 10;
  constructor(a, b) {
    this.a = a;
    this.b = b;
  }
 
  init() {
    console.log(this.a + this.b + Src.s)
  }
}
new Src('a', 'b').init();
 
// 新数组方法
const array1 = [5, 12, 50, 130, 44];
const isLargeNumber = (element) => element > 45;
console.log(array1.findLastIndex(isLargeNumber));
 
// 可选连
const obj = {}
console.log(obj?.fn?.());
 
// tc39 在提案中的新语法 绑定运算符
const box = {
  weight: 2,
  getWeight() {
    return this.weight;
  },
};
const { getWeight } = box;
console.log(box.getWeight()); // prints '2'
const bigBox = { weight: 10 };
console.log(bigBox::getWeight()); // prints '10'
// Can be chained:
function add(val) {
  return this + val;
}
console.log(bigBox::getWeight()::add(5)); // prints '15'
 
  1. 运行 yarn dev 然后就能到 ./lib文件下看到编译的结果

浏览器 示例

  1. 创建项目
mkdir /browser-babel-test
cd /browser-babel-test
yarn init -y
yarn add  @babel/core @babel/preset-env babel-loader core-js cross-env @babel/plugin-proposal-function-bind  express html-webpack-plugin webpack webpack-cli webpack-dev-server -D
  1. 编写打包命令
"scripts": {
    "dev": "cross-env NODE_ENV=development webpack-dev-server --config webpack.config.js",
    "build": "cross-env NODE_ENV=production webpack --config webpack.config.js",
    "start": "node server.js"
},
  1. 编写babel.config.js 配置文件
module.exports = {
  presets: [
    [
      '@babel/preset-env',
      {
        targets: {
          ie: 10,  // 编译成 ie10 能识别的语法
        },
        useBuiltIns: 'usage',
        corejs: "3.25.5",
      }
    ]
  ],
  plugins: ['@babel/plugin-proposal-function-bind']
}
  1. 在当前项目跟目录下创建 public文件夹和index.html文件 作为静态资源文件入口 /public/index.html
  2. 在当前项目跟目录下创建 src文件夹和index.js文件 作为入口文件 /src/index.js
// 以下为测试代码    主要是测试语法 可选链、Array的新api findLastIndex   以及在提案阶段的 绑定运算符 语法
console.log('当前环境--》', process.env.NODE_ENV)
const array1 = [5, 12, 50, 130, 44];
const isLargeNumber = (element) => element > 45;
console.log(array1.findLastIndex(isLargeNumber));
const obj = {}
console.log(obj?.fn?.());
// tc39 在提案中的新语法 绑定运算符
const box = {
  weight: 2,
  getWeight() {
    return this.weight;
  },
};
const { getWeight } = box;
console.log(box.getWeight()); // prints '2'
const bigBox = { weight: 10 };
console.log(bigBox::getWeight()); // prints '10'
// Can be chained:
function add(val) {
  return this + val;
}
console.log(bigBox::getWeight()::add(5)); // prints '15'
  1. 在当前项目跟目录下创建 server.js 作为线上演示服务端文件
const express = require('express');
const app = express();
app.use(express.static('dist'));
const port = 7008;
app.listen(port);
console.log(`http://localhost:${port}`);
 
  1. 编写 webpack.config.js 配置文件
const path = require('path');
const HtmlWebpackPlugins = require('html-webpack-plugin');
 
module.exports = {
  // 模式
  mode: process.env.NODE_ENV,
  // 运行环境
  target: ['web', 'es5'],
  // 入口
  entry: path.join(__dirname, './src/index.js'),
  // 出口
  output: {
    clean: true,
    path: path.join(__dirname, 'dist'),
    filename: '[name].[fullhash].bundle.js',
  },
  // 语法转换
  module: {
    rules: [
      {
        exclude: path.join(__dirname, 'node_modules'),
        test: /\.js$/,
        loader: 'babel-loader',
        // use: {
        //   options: {
        //     如果你想自定义你的 babel 配置文件的名称和位置 参考以下配置
        //     configFile: path.join(__dirname, './babel.config.js')
        //   }
        // }
      }
    ]
  },
  // 插件
  plugins: [
    // 打包出来的js文件 添加到 html 中
    new HtmlWebpackPlugins({
      template: path.join(__dirname, './public/index.html'),
    })
  ],
  // 开发服务器
  devServer: {
    port: 8001
  }
}

Babel 部分包作用

/*
* 如果使用webpack就不要这个包   使用babel-loader 就可以了
1. @babel/cli                             命令解析包
2. @babel/core                            babel的核心包
3. @babel/preset-env                      babel 智能预设语法的包 对新语法做编译转换
4. core-js                                polyfill 新语法API做垫片
5. babel-loader                           webpack的loader插件
6. @babel/plugin-proposal-function-bind   tc39提案的 绑定运算符
 */

Babel 配置文件讲解

Babel 配置文档 (opens in a new tab)

Presets 部分讲解

  1. Presets 预设文档 (opens in a new tab)
/*
*  babel提供4种语法预设    允许自定义扩展
   @babel/preset-env 用于编译 ES2015+ 语法
   @babel/preset-typescript 用于 TypeScript
   @babel/preset-react 用于 React
   @babel/preset-flow 用于 Flow
* */
// 用法
{
  presets: [
    "@babel-preset-react",
    [
      "@babel/preset-env",
      {
        // 参数有很多,先学基本的几个
        targets: {
          ie: 10,
        },
        corejs: '3.25.5', // 对应你安装的 core-js版本
        useBuiltIns: 'usage', // babel 会根据目标环境 来判断是否需要对语法做转换 和添加垫片
      }
    ]
  ]
}
  1. @babel/preset-env 配置文档 (opens in a new tab)
  2. @babel/preset-env 的 target 配置文档 (opens in a new tab)
  3. @babel/preset-env 的 useBuiltIns 配置文档 (opens in a new tab)
  4. core-js (opens in a new tab)

Plugins 部分讲解

  1. Plugins 预设文档 (opens in a new tab)
  2. Plugins List 插件列表 (opens in a new tab)
/*
*  babel 提供多种插件 具体看插件列表
* */
// 用法
{
  plugins: ["@babel/plugin-proposal-function-bind"]
}