聊一聊Babel7.x+Webpack(babel7.4+的使用感受

Babel

它是一個編譯器可以讓你使用最新版本的ES規(guī)范比如ES2015(ES6),ES2016(ES7),ES2017(ES8)的寫法并把它編譯成老的ES5的寫法。

首先babel的轉(zhuǎn)換其實做了兩件事情

  • 語法轉(zhuǎn)換
let array = [1, 2, 3, 4, 5, 6];
array.includes(item => item > 2);
----------------------------> 轉(zhuǎn)換后

var array = [1, 2, 3, 4, 5, 6];
array.includes(function (item) {
  return item > 2;
}); 
  • 新API的polyfill兼容
let array = [1, 2, 3, 4, 5, 6];
array.includes(item => item > 2);
new Promise()

async function a(){
    console.log(1);
}


--------------------------->轉(zhuǎn)換后
"use strict";

require("regenerator-runtime/runtime");

require("core-js/modules/es6.promise");

require("core-js/modules/es6.object.to-string");

require("core-js/modules/es7.array.includes");

var array = [1, 2, 3, 4, 5, 6];
array.includes(function (item) {
  return item > 2;
});
new Promise();

function a() {
  return regeneratorRuntime.async(function a$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          console.log(1);

        case 1:
        case "end":
          return _context.stop();
      }
    }
  });
}

但是但是,"平平無奇"的babel本身只會轉(zhuǎn)義語法,但是我們還想用Promise,Object.assign等等。所以就會有這么大一堆不明所以的東西

@babel/polyfill,@babel/preset-env,@babel/plugin-transform-runtime,@babel/runtime

@babel/polyfill

很容易理解,它就是各種API墊片,只要在主入口引用import '@babel/polyfill',就能完美使用各種新的API,完全沒有任何需要配置的地方。

但是但是,這樣就是把整個第三方墊片引入,打包出來會非常的大。所以就用到接下來的@babel/preset-env

@babel/preset-env

@babel/preset-env 主要干的事情呢,根據(jù)你的設置表示你要啥,它就給你啥,不多給也不少給。
使用@babel/preset-env最主要的配置字段就是useBuiltInstarget

//babel.config.js
const presets = [
  [
    "@babel/env",
    {
      targets: {
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      },
      useBuiltIns: "usage",
    },
  ],
];

module.exports = { presets };

target

target表示所以編譯的代碼運行的環(huán)境,可以是瀏覽器,可以是node,只要設置相應的字段,它就能根據(jù)規(guī)則插入和轉(zhuǎn)義相應的語法跟API

例如以下的"browsers": ["> 1%", "last 2 versions", "not ie <= 8"]表示兼容市場占有率>1%,瀏覽器的最新兩個版本,ie8以下不兼容

useBuiltIns

useBuiltIns有三種取值,不同的取值會影響API的導入方式

  • false

    就是不用polyfill,如果在業(yè)務入口 import '@babel/polyfill', 會無視 .browserslist 將所有的 polyfill 加載進來。

  • entry

    需要手動import '@babel/polyfill',它會根據(jù)targets中的配置來過濾出polyfill

  • usage

    不需要手動import '@babel/polyfill'(加上也無妨,編譯時會自動去掉), 且它會根據(jù)targets中的配置來過濾出polyfill + 業(yè)務代碼使用到的新 API 按需進行 polyfill。

    useage并不會對第三方包做檢測,所以如果某些第三包使用高級的API那么在低版本的瀏覽器上也是會報錯的,例如:Array.from

基本上的開發(fā)使用@babel/preset-env+@babel/polyfill已經(jīng)完全很完美了

但是以上看起來好完美,但是還有一個巨大問題!?。?/strong>

"use strict";

require("regenerator-runtime/runtime");

require("core-js/modules/es6.promise");

require("core-js/modules/es6.object.to-string");

require("core-js/modules/es7.array.includes");

var array = [1, 2, 3, 4, 5, 6];
array.includes(function (item) {
  return item > 2;
});
new Promise();

function a() {
  return regeneratorRuntime.async(function a$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          console.log(1);

        case 1:
        case "end":
          return _context.stop();
      }
    }
  });
}

以上所有的墊片的導入都是直接掛載在全局對象上的,對于寫業(yè)務API的時候這樣并不影響使用,但是如果對于開發(fā)第三方包的情況,babel-polyfill 會污染全局變量,給很多類的原型鏈上都作了修改,這種情況就會變得非常不可控。

@babel/plugin-transform-runtime和@babel/runtime 讓Babel在更進一步

更改babel配置

const presets = [
  [
    "@babel/env",
    {
      targets: {
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      },
      // useBuiltIns: "usage",
    },
  ],
];

const plugins = [
  [
    "@babel/plugin-transform-runtime",
    {
      "corejs": false,
      "helpers": true,
      "regenerator": true,
      "useESModules": false
    }
  ]
]

module.exports = { presets,plugins };

其中的corejs參數(shù)有坑,后面說!

我們在來看看打包結果

"use strict";

var _interopRequireDefault = require("@babel/runtime-corejs2/helpers/interopRequireDefault");

var _regenerator = _interopRequireDefault(require("@babel/runtime-corejs2/regenerator"));

var _promise = _interopRequireDefault(require("@babel/runtime-corejs2/core-js/promise"));

// import "@babel/polyfill"
var array = [1, 2, 3, 4, 5, 6];
array.includes(function (item) {
  return item > 2;
});
new _promise.default();

function a() {
  return _regenerator.default.async(function a$(_context) {
    while (1) {
      switch (_context.prev = _context.next) {
        case 0:
          console.log(1);

        case 1:
        case "end":
          return _context.stop();
      }
    }
  });
}

是不是很神奇所有的新api都包裹在一個對象里,沒有去污染全局變量。

soga,既然這么神奇,為嘛不直接一步到位用這種方法呢?

我們仔細一點看的話,發(fā)現(xiàn)下面的代碼并沒有被轉(zhuǎn)化,這就是babel/plugin-transform-runtime的缺點了,它并沒有去轉(zhuǎn)義實例新API的方法,如果在代碼里使用到了新API的實例方法,這里是會跪的。

var array = [1, 2, 3, 4, 5, 6];
array.includes(function (item) {
  return item > 2;
});

還需要留意的一點,在package.json下@babel/plugin-transform-runtime是在devDependencies,@babel/runtime是在dependencies下(因為里面都是轉(zhuǎn)化的API墊片)

  "devDependencies": {
    "@babel/plugin-transform-runtime": "^7.7.6",
  },
  "dependencies": {
    "@babel/runtime": "^7.7.6"
  }

@babel/runtime內(nèi)部集成了

  • core-js

    轉(zhuǎn)換一些內(nèi)置類 (Promise, Symbols等等) 和靜態(tài)方法 (Array.from 等)。絕大部分轉(zhuǎn)換是這里做的。自動引入

  • regenerator

    作為 core-js 的拾遺補漏,主要是 generator/yield 和 async/await 兩組的支持。當代碼中有使用 generators/async 時自動引入。

最后大殺器,無敵巨坑:corejs3

我們應該經(jīng)常在其他文檔和使用說明中看到 runtime 不支持實例方法,確實在之前的使用中,無論是 Babel 7.0.0 ~ 7.4.0 抑或 Babel < 7.0.0, 對此都無能為力。只能通過配置 corejs (可選 false | 2)來決定是否使用 babel/runtime-corejs 替代core-js 抑或 polyfill (可選 true | false)來決定是否全局引入新的內(nèi)置函數(shù)(new built-ins),然而其實這兩者并沒有根本改變, corejs: 2 實際上等同于 7.0.0 版本之前的 polyfill: true。
重點: 真正的改變出現(xiàn)在 Babel 7.4.0 之后,你可以選擇引入 @babel/runtime-corejs3,設置 corejs: 3 來幫助您實現(xiàn)對實例方法的支持。

如果在Babel 7.4之后的版本,更改配置corejs : 3

const plugins = [
  [
    "@babel/plugin-transform-runtime",
    {
      "corejs": 3,   //"corejs": false // 可選 false | 2 | 3
      "helpers": true,
      "regenerator": true,
      "useESModules": false
    }
  ]
]

module.exports = { presets,plugins };

在看轉(zhuǎn)化結果

var _includes = _interopRequireDefault(require("@babel/runtime-corejs3/core-js-stable/instance/includes"));

var array = [1, 2, 3, 4, 5, 6];
(0, _includes.default)(array).call(array, function (item) {
  return item > 2;
});

它連實例API都轉(zhuǎn)了,(早干嘛去了,前端ER真的學不動了?。。。?/p>

最后附上Webpack版本Babel配置

{
    "presets": [
        [
            "@babel/preset-env",
            targets: {
                "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
            },
        ],
    ],
    "plugins": [
        ["@babel/plugin-transform-runtime", {
            "corejs": 3
        }]
    ]
}
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容