babel 之再次複習

再複習一次。

簡述

先安裝 3 個東西:

  • @babel/core
  • @babel/cli
  • @babel/preset-env

裝完後 package.json 應該要長這樣:

1
2
3
4
5
"devDependencies": {
"@babel/cli": "^7.17.6",
"@babel/core": "^7.17.5",
"@babel/preset-env": "^7.16.11",
}

接著在根目錄建立 .babel.config.json,用來設定 preset 的資訊:

1
2
3
{
"presets": ["@babel/preset-env"]
}

這支檔案裡面可以寫一些設定,例如說要支援 0.25% 人在使用的瀏覽器就會這樣寫:

1
2
3
4
5
6
7
8
9
10
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "entry"
}
]
]
}

通常預設的設定就很夠用了,所以沒特殊需求的話不用改。

實際使用

接著來寫一些 ES6 的東西,看用 babel 轉完後會變怎樣:

1
2
3
4
5
6
7
const a = 1;
const b = [1, 2, 3, 4];
const c = [...b];

for (let n of c) {
console.log(n);
}

接著執行 babel:

1
2
3
4
# 透過 package.json 執行 babel src -d lib
npm run build
# 透過 npx
npx babel src -d lib

輸出結果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
"use strict";

function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

var a = 1;
var b = [1, 2, 3, 4];
var c = [].concat(b);

var _iterator = _createForOfIteratorHelper(c),
_step;

try {
for (_iterator.s(); !(_step = _iterator.n()).done;) {
var n = _step.value;
console.log(n);
}
} catch (err) {
_iterator.e(err);
} finally {
_iterator.f();
}

看起來亂七八糟的,但不要緊!這是 babel 為了支援舊的瀏覽器而加上的程式碼。

總之呢,只要引入這支檔案就能支援舊的瀏覽器囉!

gulp 的使用方法 mentor-program-day76
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×