babel-loader 使用指南

本指南基於 babel 7javascript

安裝

yarn add babel-loader @babel/core -D
複製代碼

使用

{
  test: /\.js$/,
  loader: 'babel-loader',
  include: [
    path.resolve(__dirname, '../src')
  ]
}
複製代碼

該配置指明瞭使用 babel 翻譯 js 文件,但僅是這樣 babel 並不知道該如何翻譯、翻譯什麼,要讓它正真工做起來,還須要其餘插件支持。java

預設

上文說到咱們須要使用一些插件,但搜索和選擇插件是一個很浪費時間的事,爲了在短期內解決問題,咱們就須要使用預設react

預設就是指插件(及其配置)組成的數組,它能夠包含插件和其餘預設,例如:git

yourPreset.jsgithub

module.exports = function() {
  return {
    presets: [
      require('@babel/preset-env'),
    ],
    plugins: [
      require('pluginA'),
      require('pluginB')
    ]
  }
}
複製代碼

babel 提供幾個官方預設供用戶使用,這裏舉例講解最經常使用的 @babel/preset-env,除此以外還有:chrome

@babel/preset-env 會根據你的環境配置,把 ES6+ 代碼翻譯成環境能支持的 ES5 代碼,因此咱們只須要配置項目的目標環境,就能放心地使用新語法特性。typescript

  1. 安裝json

    yarn add @babel/preset-env -D
    複製代碼
  2. 配置數組

    {
      test: /\.js$/,
      loader: 'babel-loader',
      include: [
        path.resolve(__dirname, '../src')
      ],
      // +++
      options: {
        presets: [
          [
            '@babel/preset-env',
            {
              targets: {
                chrome: '51',
                ie: '9'
              },
              modules: false,
              useBuiltIns: 'entry',
              corejs: 2
            }
          ]
        ]
      }
      // +++
    }
    複製代碼

    useBuiltIns 值不爲 false 時須要指明 corejs 版本,不然會有警告(雖然有默認值 2)bash

    corejs: 2 表示使用 @babel/preset-env/lib/polyfills/corejs2 來翻譯 / 填充代碼

useBuiltIns 選項說明:

  • false 默認值,babel 不自動導入 polyfill ,你須要手動在項目全局環境中導入
    • 缺點:每一個語法都去找其對應的 polyfill 很麻煩,直接 import babel-polyfill 時同 useBuiltIns: entry
  • entry 須要你在入口文件 import @babel/polyfill',它會依據環境設置,僅導入環境不支持的 polyfill
    • 優勢:只導入環境不支持的 polyfill
    • 缺點:須要手動導入 @babel/polyfill
  • usage 當每一個文件裏用到須要 polyfill 的特性時,在文件中添加對應的 polyfill ,能夠保證每一個 polyfill 只 load 一次,縮小生產包體積
    • 優勢:只導入須要的 polyfill 而且是自動導入
    • 缺點:實驗中的屬性

@babel/preset-env 使用起來很是方便,但遺憾的是它並不能覆蓋全部開發場景,由於它存在兩個缺點:

  • 重複填充: @babel/preset-env 會填充每個文件,因此 a.js / b.js 若是同時用到了 Promise,那麼翻譯後兩個文件均存在 Promise 的填充
  • 全局污染: @babel/preset-env 會將 Promise 翻譯成全局變量 var _Promise

若是你打包生成的是公共庫,就不能僅僅使用 @babel/preset-env,由於你不能控制這個包的使用環境,對全局變量的污染或許會製造一些問題。

transform-runtime

以上兩個問題咱們能夠藉助插件 @babel/plugin-transform-runtime 來解決

This is where the @babel/plugin-transform-runtime plugin comes in: all of the helpers will reference the module @babel/runtime to avoid duplication across your compiled output. The runtime will be compiled into your build.

Another purpose of this transformer is to create a sandboxed environment for your code. If you use @babel/polyfill and the built-ins it provides such as Promise, Set and Map, those will pollute the global scope. While this might be ok for an app or a command line tool, it becomes a problem if your code is a library which you intend to publish for others to use or if you can't exactly control the environment in which your code will run.

  1. 安裝
    yarn add @babel/plugin-transform-runtime -D // 開發依賴
    yarn add @babel/runtime-corejs2 // 生產依賴
    複製代碼
  2. 配置
    {
      test: /\.js$/,
      loader: 'babel-loader',
      include: [
        path.resolve(__dirname, '../src')
      ],
      // +++
      options: {
        plugins: [
          [
            '@babel/plugin-transform-runtime',
            {
              'corejs': 2,
              'absoluteRuntime': false,
              'helpers': true,
              'regenerator': true,
              'useESModules': false
            }
          ]
        ]
      }
      // +++
    }
    複製代碼
    'corejs': 2 表示使用 @babel/runtime-corejs2 來翻譯 / 填充代碼,默認 false 表示本身引入 polyfill

須要注意的是, @babel/plugin-transform-runtime 因爲其不污染全局變量的特性,沒法翻譯對象的實例方法,好比 Array.includes / Array.from

如何選擇

若是項目是公共庫,使用 @babel/plugin-transform-runtime ,不然使用 @babel/preset-env

經常使用配置

yarn add babel-loader @babel/core @babel/preset-env @babel/plugin-syntax-dynamic-import -D
複製代碼

在 .babelrc 中配置

.babelrc 放在項目根目錄

{
  test: /\.js$/,
  loader: 'babel-loader',
  include: [
    path.resolve(__dirname, '../src')
  ],
  options: {
    cacheDirectory: true
  }
}
複製代碼

.babelrc

{
  "presets": [
    [
      "@babel/preset-env",
      {
        "modules": false,
        "useBuiltIns": "usage",
        "targets": {
          "chrome": "58"
        },
        "corejs": 2
      }
    ]
  ],
  "plugins": [
    "@babel/plugin-syntax-dynamic-import"
  ]
}
複製代碼

在 JS 中配置

yarn add babel-loader @babel/core @babel/plugin-transform-runtime @babel/plugin-syntax-dynamic-import -D
yarn add @babel/runtime-corejs2
複製代碼
{
  test: /\.js$/,
  loader: 'babel-loader',
  include: [
    path.resolve(__dirname, '../src')
  ],
  options: {
    cacheDirectory: true,
    presets: [
      [
        '@babel/preset-env',
        {
          modules: false,
          useBuiltIns: 'usage',
          targets: {
            chrome: '58'
          },
          corejs: 2
        }
      ]
    ],
    plugins: [
      '@babel/plugin-syntax-dynamic-import'
    ]
  }
}
複製代碼

參考文檔

相關文章
相關標籤/搜索