esnextES6 转 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');
评论