babel知多少

媒介

ES2015/ES2016/ES2017等新语法,新API的涌现让前端写起来更爽,更不用说考虑到面向将来编码。可我们运用这些新语法,新API,代码的运转兼容性必将受到影响。babel的合时涌现,处理了我们运用next generation JavaScript的挂念!它多是我们最常运用的JavaScript转码东西了,但是你真的相识它的运用了吗?

从TC39提及

TC39是ECMAScript范例的设想制订构造,它的成员包括主流浏览器厂商,它现实推进着JavaScript言语的生长的。我们晓得,ECMAScript是范例,而JavaScript言语是参照ECMAScript范例的完成。

  • 1997年,产出ECMAScript。原由是1996岁尾,Netscape公司将JavaScript提交给ECMA International构造对JavaScript言语举行规范化。

  • 1998年,宣布ECMAScript2

  • 1999年,宣布ECMAScript3,成为JavaScript的通行规范,得到了各浏览器厂商的普遍支撑。

  • 2009年,宣布ECMAScript5,其间,ECMAScript4由于改版过于激进,半途短命。

  • 2015年,ECMAScript6宣布,也称为ES2015,ES.Harmony

  • 2016年,ECMAScript7宣布,也称为ES2016,ES.Next

  • 2017年,ECMAScript8宣布,也称为ES2017

TC39 Process划定了每项新特征归入范例的历程,分为5个阶段

  • stage0: strawman,能够明白成idea迸发

  • stage1: proposal,也就是书面化产出一个提案

  • stage2: draft,产出范例的草案

  • stage3: candidate,该特征进入候选阶段

  • stage4: finished,会尽快随版正式宣布

将来,按商定每年会继承宣布一个版本,貌似也预示着JavaScript社区的活泼。言语范例迭代这么快,对老版本浏览器的支撑这项荣耀而巨大的使命就交给了babel。

常常使用的babel packages

babel-core

babel转码器,供应转码API,babel-core虽然常常使用,但一样平常开辟很少直接挪用,webpack中运用babel-loader加载js,babel-loader实在会直接挪用babel-core API对文件举行转码。

babel.transform(code: string, options?: Object)

babel.transformFile(filename: string, options?: Object, callback: Function)

babel.transformFileSync(filename: string, options?: Object)

babel.transformFromAst(ast: Object, code?: string, options?: Object)

babel-cli

重要用于babel转码的命令行挪用,前端项目基础已离不开webpack,所以babel-cli经常常使用于node项目中的build,由于我们能够会写async/await,但我们的服务端环境是V6.x

babel app --out-dir webapp

babel-polyfill

babel默许只做转码,ployfill的事情(比方一些新内置对象、新的静态要领、实例要领),须要在运转进口惹人babel-polyfill来支撑,为运转环境供应垫片支撑。

须要polyfill:

module.exports = {
  builtins: {
    Symbol: "symbol",
    Promise: "promise",
    Map: "map",
    WeakMap: "weak-map",
    Set: "set",
    WeakSet: "weak-set",
    Observable: "observable",
    setImmediate: "set-immediate",
    clearImmediate: "clear-immediate",
    asap: "asap"
    //parseFloat: "parse-float", // temporary disabled
    //parseInt: "parse-int" // temporary disabled
  },

  methods: {
    Array: {
      concat: "array/concat", // deprecated
      copyWithin: "array/copy-within",
      entries: "array/entries",
      every: "array/every",
      fill: "array/fill",
      filter: "array/filter",
      findIndex: "array/find-index",
      find: "array/find",
      forEach: "array/for-each",
      from: "array/from",
      includes: "array/includes",
      indexOf: "array/index-of",
      //isArray: "array/is-array", // temporary disabled
      join: "array/join",
      keys: "array/keys",
      lastIndexOf: "array/last-index-of",
      map: "array/map",
      of: "array/of",
      pop: "array/pop", // deprecated
      push: "array/push", // deprecated
      reduceRight: "array/reduce-right",
      reduce: "array/reduce",
      reverse: "array/reverse", // deprecated
      shift: "array/shift", // deprecated
      slice: "array/slice", // deprecated
      some: "array/some",
      sort: "array/sort",
      splice: "array/splice",
      unshift: "array/unshift", // deprecated
      values: "array/values"
    },

    JSON: {
      stringify: "json/stringify"
    },

    Object: {
      assign: "object/assign",
      create: "object/create",
      defineProperties: "object/define-properties",
      defineProperty: "object/define-property",
      entries: "object/entries",
      freeze: "object/freeze",
      getOwnPropertyDescriptor: "object/get-own-property-descriptor",
      getOwnPropertyDescriptors: "object/get-own-property-descriptors",
      getOwnPropertyNames: "object/get-own-property-names",
      getOwnPropertySymbols: "object/get-own-property-symbols",
      getPrototypeOf: "object/get-prototype-of",
      isExtensible: "object/is-extensible",
      isFrozen: "object/is-frozen",
      isSealed: "object/is-sealed",
      is: "object/is",
      keys: "object/keys",
      preventExtensions: "object/prevent-extensions",
      seal: "object/seal",
      setPrototypeOf: "object/set-prototype-of",
      values: "object/values"
    },

    RegExp: {
      escape: "regexp/escape" // deprecated
    },

    Math: {
      acosh: "math/acosh",
      asinh: "math/asinh",
      atanh: "math/atanh",
      cbrt: "math/cbrt",
      clz32: "math/clz32",
      cosh: "math/cosh",
      expm1: "math/expm1",
      fround: "math/fround",
      hypot: "math/hypot",
      imul: "math/imul",
      log10: "math/log10",
      log1p: "math/log1p",
      log2: "math/log2",
      sign: "math/sign",
      sinh: "math/sinh",
      tanh: "math/tanh",
      trunc: "math/trunc",
      iaddh: "math/iaddh",
      isubh: "math/isubh",
      imulh: "math/imulh",
      umulh: "math/umulh"
    },

    Symbol: {
      for: "symbol/for",
      hasInstance: "symbol/has-instance",
      isConcatSpreadable: "symbol/is-concat-spreadable",
      iterator: "symbol/iterator",
      keyFor: "symbol/key-for",
      match: "symbol/match",
      replace: "symbol/replace",
      search: "symbol/search",
      species: "symbol/species",
      split: "symbol/split",
      toPrimitive: "symbol/to-primitive",
      toStringTag: "symbol/to-string-tag",
      unscopables: "symbol/unscopables"
    },

    String: {
      at: "string/at",
      codePointAt: "string/code-point-at",
      endsWith: "string/ends-with",
      fromCodePoint: "string/from-code-point",
      includes: "string/includes",
      matchAll: "string/match-all",
      padLeft: "string/pad-left", // deprecated
      padRight: "string/pad-right", // deprecated
      padStart: "string/pad-start",
      padEnd: "string/pad-end",
      raw: "string/raw",
      repeat: "string/repeat",
      startsWith: "string/starts-with",
      trim: "string/trim",
      trimLeft: "string/trim-left",
      trimRight: "string/trim-right",
      trimStart: "string/trim-start",
      trimEnd: "string/trim-end"
    },

    Number: {
      EPSILON: "number/epsilon",
      isFinite: "number/is-finite",
      isInteger: "number/is-integer",
      isNaN: "number/is-nan",
      isSafeInteger: "number/is-safe-integer",
      MAX_SAFE_INTEGER: "number/max-safe-integer",
      MIN_SAFE_INTEGER: "number/min-safe-integer",
      parseFloat: "number/parse-float",
      parseInt: "number/parse-int"
    },

    Reflect: {
      apply: "reflect/apply",
      construct: "reflect/construct",
      defineProperty: "reflect/define-property",
      deleteProperty: "reflect/delete-property",
      enumerate: "reflect/enumerate", // deprecated
      getOwnPropertyDescriptor: "reflect/get-own-property-descriptor",
      getPrototypeOf: "reflect/get-prototype-of",
      get: "reflect/get",
      has: "reflect/has",
      isExtensible: "reflect/is-extensible",
      ownKeys: "reflect/own-keys",
      preventExtensions: "reflect/prevent-extensions",
      setPrototypeOf: "reflect/set-prototype-of",
      set: "reflect/set",
      defineMetadata: "reflect/define-metadata",
      deleteMetadata: "reflect/delete-metadata",
      getMetadata: "reflect/get-metadata",
      getMetadataKeys: "reflect/get-metadata-keys",
      getOwnMetadata: "reflect/get-own-metadata",
      getOwnMetadataKeys: "reflect/get-own-metadata-keys",
      hasMetadata: "reflect/has-metadata",
      hasOwnMetadata: "reflect/has-own-metadata",
      metadata: "reflect/metadata"
    },

    System: {
      global: "system/global"
    },

    Error: {
      isError: "error/is-error" // deprecated
    },

    Date: {
      //now: "date/now" // temporary disabled
    },

    Function: {
      // Warning: /virtual/ method - prototype, not static, version
      //bind: "function/virtual/bind" // temporary disabled
    }
  }
};

babel-register

惹人后,require要领会被重写并绑定一个hook到babel的complier,也就是说当再次经由过程require加载其他剧本文件时会在运转时自动经由过程babel转码之。不实用与临盆环境。

require('require-register');
const file = require('file.es'); // 援用的文件会在运转时自动转码

.babelrc

经由过程在.babelrc文件中指定转码plugin,babel才到达指定特征的转码结果。

{
    plugins: [
        'transform-es2015-arrow-functions',
        'transform-es2015-block-scoped-functions'
    ]
}

一个一个plugin增加能够很贫苦?babel供应了preset,它能够明白为plugin的组合,你能够如许建立一个preset:

  1. 为你的preset建立一个git堆栈,比方babel-preset-mynamepreset

  2. git clone <堆栈地点>

  3. 目次构造很简单,以下

  4. 编辑index.js

  5. 宣布到npm堆栈

// 目次构造
- package.json
    |
- src
    |-- index.js
// index.js
import arrowFunctions from "babel-plugin-transform-es2015-arrow-functions";
import blockScopedFunctions from "babel-plugin-transform-es2015-block-scoped-functions";

export default {
  plugins: [
    arrowFunctions,
    blockScopedFunctions
  ]
};

固然,社区有相对更成熟的presets,能够直接援用, 比方

  • babel-preset-es2015

  • babel-preset-stage-0

  • babel-preset-stage-1

  • babel-preset-stage-2

  • babel-preset-stage-3

  • babel-preset-es2016

  • babel-preset-es2017

  • babel-preset-latest

能够按需挑选运用~

    原文作者:JrayZhang
    原文地址: https://segmentfault.com/a/1190000010411116
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞