esnext - ES6 轉 JavaScript

jopen 10年前發布 | 30K 次閱讀 esnext JavaScript開發

esnext 是一個 JavaScript 庫,可以將 ES6 草案規范語法轉成今天的 JavaScript 語法。

例如:

/*
On the left is code written with new JavaScript features,
and on the right is the console output, plus the same code
re-written so it can run in today's browsers.

Edits made to the code on the left will re-generate and
re-run the code on the right. Try it out!
*/

// Classes
class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  get name() {
    // Template strings
    return `${this.firstName} ${this.lastName}`;
  }

  toString() {
    return this.name;
  }
}

console.log(
  'Full name is:',
  new Person('Michael', 'Bluth')
);

// Arrow functions
console.log([1, 2, 3].map(x => x * x));

// Rest params
function join(delim, ...items) {
  return items.join(delim);
}

// Spread args
console.log(join('-', ...[415, 555, 1212]));

將被轉換成:

/*
On the left is code written with new JavaScript features,
and on the right is the console output, plus the same code
re-written so it can run in today's browsers.

Edits made to the code on the left will re-generate and
re-run the code on the right. Try it out!
*/

// Classes
var $__Array$prototype$slice = Array.prototype.slice;
var $__Object$defineProperties = Object.defineProperties;

var Person = function() {
  "use strict";

  function Person(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  $__Object$defineProperties(Person.prototype, {
    name: {
      get: function() {
        // Template strings
        return "" + this.firstName + " " + this.lastName + "";
      },

      enumerable: true,
      configurable: true
    },

    toString: {
      value: function() {
        return this.name;
      },

      enumerable: false,
      writable: true
    }
  });

  $__Object$defineProperties(Person, {});
  return Person;
}();

console.log(
  'Full name is:',
  new Person('Michael', 'Bluth')
);

// Arrow functions
console.log([1, 2, 3].map(function(x) {
  return x * x;
}));

// Rest params
function join(delim) {
  var $__arguments = arguments;
  var items = [].slice.call($__arguments, 1);
  return items.join(delim);
}

// Spread args
console.log(join.apply(null, ['-'].concat($__Array$prototype$slice.call([415, 555, 1212]))));

使用方法:

var transpiler = require('es6-module-transpiler');
var Container = transpiler.Container;
var FileResolver = transpiler.FileResolver;
var BundleFormatter = transpiler.formatters.bundle;

var container = new Container({
  resolvers: [new FileResolver(['lib/'])],
  formatter: new BundleFormatter()
});

container.getModule('index');
container.write('out/mylib.js');

項目主頁:http://www.baiduhome.net/lib/view/home/1413191880172

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!