本文共 2538 字,大约阅读时间需要 8 分钟。
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 codere-written so it can run in today's browsers.Edits made to the code on the left will re-generate andre-run the code on the right. Try it out!*/// Classesclass 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 functionsconsole.log([1, 2, 3].map(x => x * x));// Rest paramsfunction join(delim, ...items) { return items.join(delim);}// Spread argsconsole.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 codere-written so it can run in today's browsers.Edits made to the code on the left will re-generate andre-run the code on the right. Try it out!*/// Classesvar $__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 functionsconsole.log([1, 2, 3].map(function(x) { return x * x;}));// Rest paramsfunction join(delim) { var $__arguments = arguments; var items = [].slice.call($__arguments, 1); return items.join(delim);}// Spread argsconsole.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');