Compare commits
161 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f1328aa82f | ||
|
|
e298a5d350 | ||
|
|
89a6ef0b26 | ||
|
|
c7ac9b7815 | ||
|
|
55c99b9122 | ||
|
|
545c8c3adb | ||
|
|
d093dc8231 | ||
|
|
eaf9d58b8d | ||
|
|
6131cea5b2 | ||
|
|
ca4831febe | ||
|
|
9cf8d05a19 | ||
|
|
2a4f03330b | ||
|
|
83bc614bad | ||
|
|
99ccb4111a | ||
|
|
f6c72e9ae9 | ||
|
|
a90730d4bf | ||
|
|
29503d2d37 | ||
|
|
35451ed408 | ||
|
|
7167aeb65a | ||
|
|
29d0489443 | ||
|
|
82aa2686f9 | ||
|
|
24616fa08a | ||
|
|
9f3e1eabfd | ||
|
|
286d2f84bd | ||
|
|
7fc484d82e | ||
|
|
ad6ab57fe3 | ||
|
|
348fe045d3 | ||
|
|
980b20316b | ||
|
|
5b52e507ca | ||
|
|
9853c9d78d | ||
|
|
72ec771725 | ||
|
|
75e97d9f7e | ||
|
|
295faf185c | ||
|
|
54b05f33f2 | ||
|
|
1985146760 | ||
|
|
13a52dd300 | ||
|
|
9d4bea70e6 | ||
|
|
421906bcc1 | ||
|
|
508b3531e5 | ||
|
|
c67c407cd0 | ||
|
|
aa552fea0d | ||
|
|
9bbf109dc8 | ||
|
|
393d52088a | ||
|
|
5783973734 | ||
|
|
55e01afd0d | ||
|
|
1231dc6cef | ||
|
|
b08f2061b5 | ||
|
|
1536d3de91 | ||
|
|
fddacb1612 | ||
|
|
9d1ff2b71b | ||
|
|
1c8d24f78c | ||
|
|
b619e843a9 | ||
|
|
e6a71c5849 | ||
|
|
682668c219 | ||
|
|
dd64297838 | ||
|
|
944a9d3908 | ||
|
|
d6922c9b75 | ||
|
|
fb0fcc7138 | ||
|
|
89148e6029 | ||
|
|
28d10b8eb4 | ||
|
|
3509990563 | ||
|
|
c5960fb9f7 | ||
|
|
07131576cf | ||
|
|
e75e778300 | ||
|
|
f6cb14c975 | ||
|
|
af1912ab7a | ||
|
|
8c478f29bc | ||
|
|
5b4d6d7ba9 | ||
|
|
1776b072b0 | ||
|
|
726fad1b6c | ||
|
|
23c16b0094 | ||
|
|
24f70ee4d0 | ||
|
|
fe9b0afd95 | ||
|
|
47695a8710 | ||
|
|
e1c7584280 | ||
|
|
3e63e6cd4b | ||
|
|
ba643680e5 | ||
|
|
611137c7d7 | ||
|
|
6240e5111f | ||
|
|
324a4a1b22 | ||
|
|
035f667a8f | ||
|
|
98985dd253 | ||
|
|
0a207903ce | ||
|
|
90437d262b | ||
|
|
4aba7ec192 | ||
|
|
a924c9c218 | ||
|
|
a2ed0ea9c5 | ||
|
|
c5cd729c3d | ||
|
|
b065d43a6d | ||
|
|
281003c7bd | ||
|
|
6650336c64 | ||
|
|
f904734695 | ||
|
|
0528560d81 | ||
|
|
4362ba93de | ||
|
|
ca12e87370 | ||
|
|
ebaa735adc | ||
|
|
62e406a6fe | ||
|
|
0d45a8975c | ||
|
|
8f64fe2332 | ||
|
|
a8a7587c1f | ||
|
|
7736fa11f2 | ||
|
|
d203924541 | ||
|
|
cd23e500a1 | ||
|
|
bf24a0d6b5 | ||
|
|
279d1affea | ||
|
|
2a1e012240 | ||
|
|
a307a961a6 | ||
|
|
fe5b1dc542 | ||
|
|
f057347ae9 | ||
|
|
98f2287267 | ||
|
|
e60e0e0b0e | ||
|
|
81fb8647b6 | ||
|
|
e8387c7de5 | ||
|
|
655196f3ce | ||
|
|
eef371c3df | ||
|
|
a3d21f02c6 | ||
|
|
ad4386c0ed | ||
|
|
3c82a61af1 | ||
|
|
3c154f9f6d | ||
|
|
22c972e85b | ||
|
|
6d7e14fb2b | ||
|
|
9287449372 | ||
|
|
44a35400f5 | ||
|
|
2305e2447f | ||
|
|
c420d1ffc3 | ||
|
|
fa42b076a7 | ||
|
|
0d23c1cfdb | ||
|
|
0dafdd6969 | ||
|
|
a9af8d39a2 | ||
|
|
1cc606d4d0 | ||
|
|
2a09c0a5a5 | ||
|
|
92359520cd | ||
|
|
50e5bd4680 | ||
|
|
64ef26a937 | ||
|
|
bfd6ffe471 | ||
|
|
8c1760bea2 | ||
|
|
bdb8f87480 | ||
|
|
7f6bc54920 | ||
|
|
b6af2f826d | ||
|
|
7455b6d9b9 | ||
|
|
0d2e876178 | ||
|
|
57ce1b201d | ||
|
|
5f56da457c | ||
|
|
ed988dc2bb | ||
|
|
2c471968ea | ||
|
|
fd1a91bf9c | ||
|
|
9e7de5ad2e | ||
|
|
06927288ba | ||
|
|
9342aee6bd | ||
|
|
dfa51954b8 | ||
|
|
216b8c2fd1 | ||
|
|
abc90778e8 | ||
|
|
56f1683f06 | ||
|
|
520dd7e947 | ||
|
|
17ce21509d | ||
|
|
a4c8895dc3 | ||
|
|
af4009694a | ||
|
|
941a8cc5ea | ||
|
|
359c4e8786 | ||
|
|
7ac98c1532 | ||
|
|
61c3e0a3de |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -10,3 +10,4 @@ test/tmp
|
||||
/runtime.js
|
||||
coverage
|
||||
dist
|
||||
.package.json
|
||||
|
||||
3
.gitmodules
vendored
3
.gitmodules
vendored
@@ -4,3 +4,6 @@
|
||||
[submodule "vendor/regenerator"]
|
||||
path = vendor/regenerator
|
||||
url = https://github.com/facebook/regenerator
|
||||
[submodule "vendor/test262"]
|
||||
path = vendor/test262
|
||||
url = https://github.com/tc39/test262
|
||||
|
||||
@@ -9,3 +9,4 @@ Makefile
|
||||
dist
|
||||
tests.json
|
||||
CHANGELOG.md
|
||||
.package.json
|
||||
|
||||
84
CHANGELOG.md
84
CHANGELOG.md
@@ -11,6 +11,90 @@
|
||||
|
||||
_Note: Gaps between patch versions are faulty/broken releases._
|
||||
|
||||
## 2.10.0
|
||||
|
||||
* **New Feature**
|
||||
* Add `classesFastSuper` optional transformer that doesn't support parent getters and prototype changing.
|
||||
* Add `forOfFast` transformer that speeds up `for...of` on arrays but produces more code.
|
||||
* Add `--react-compat` to `bin/6to5`.
|
||||
* **Spec Compliancy**
|
||||
* Disallow setters without a single parameter.
|
||||
* Add `configurable` and `writable` to defined properties.
|
||||
* Use define instead of assignment for class methods.
|
||||
* **Polish**
|
||||
* Fix bin name in `6to5-node --help`.
|
||||
* Fix shorthand `--whitelist` name in `bin/6to5`.
|
||||
* **Internal**
|
||||
* Hot code optimisation of traversal etc thanks to [gaearon](https://github.com/gaearon).
|
||||
|
||||
## 2.9.4
|
||||
|
||||
* **Bug Fix**
|
||||
* Support `UpdateExpression`s as `MemberExpression` objects.
|
||||
|
||||
## 2.9.3
|
||||
|
||||
* **Bug Fix**
|
||||
* Remove `exportsWildcard` helper in favor of `defaults`.
|
||||
|
||||
## 2.9.2
|
||||
|
||||
* **Bug Fix**
|
||||
* Pass `exports` to `exportWildcard` helper to allow for use inside the optional runtime.
|
||||
|
||||
## 2.9.1
|
||||
|
||||
* **Bug Fix**
|
||||
* Fix runtime generator breaking the helper inclusion loop.
|
||||
|
||||
## 2.9.0
|
||||
|
||||
* **Internal**
|
||||
* Upgrade `acorn-6to5`.
|
||||
* Now supports destructuring shorthand properties.
|
||||
|
||||
## 2.8.1
|
||||
|
||||
* **Bug Fix**
|
||||
* Fix computed accessors on object literals.
|
||||
|
||||
## 2.8.0
|
||||
|
||||
* **New Feature**
|
||||
* Add `commonStrict`, `amdStrict` and `umdStrict` module formatters that remove `module.exports` interop assignment.
|
||||
* Add `--indent` option to the 6to5 CLI.
|
||||
|
||||
## 2.7.4
|
||||
|
||||
* **Polish**
|
||||
* Inherit assignments from their declaration in destructuring.
|
||||
* Properly align multi-declarator variable declarations.
|
||||
|
||||
## 2.7.3
|
||||
|
||||
* **Polish**
|
||||
* Indent and add newlines to `React.createElement` calls in `react` transformer.
|
||||
* Remove `Object.assign` calls and replace it with an `extends` helper.
|
||||
|
||||
## 2.7.1
|
||||
|
||||
* **New Feature**
|
||||
* Expose `version` on browser and node API.
|
||||
* **Internal**
|
||||
* Upgrade `core-js` to 0.4.1
|
||||
|
||||
## 2.7.0
|
||||
|
||||
* **Spec Compliancy**
|
||||
* Disallow reassignments of imports.
|
||||
* **New Feature**
|
||||
* `reactCompat` option to enable pre-v0.12 react components.
|
||||
|
||||
## 2.6.3
|
||||
|
||||
* **Bug Fix**
|
||||
* Fix 2.6.0 regression caused by faulty export default from a source handling.
|
||||
|
||||
## 2.6.2
|
||||
|
||||
* **Bug Fix**
|
||||
|
||||
41
Makefile
41
Makefile
@@ -6,7 +6,7 @@ MOCHA_CMD = node_modules/mocha/bin/_mocha
|
||||
|
||||
export NODE_ENV = test
|
||||
|
||||
.PHONY: clean test test-cov test-clean lint test-travis test-spec test-browser publish bench build bootstrap
|
||||
.PHONY: clean test test-cov test-clean lint test-travis test-simple test-all test-browser publish build bootstrap publish-core
|
||||
|
||||
build:
|
||||
mkdir -p dist
|
||||
@@ -27,12 +27,8 @@ build:
|
||||
clean:
|
||||
rm -rf coverage templates.json test/tmp dist
|
||||
|
||||
bench:
|
||||
npm install es6-transpiler traceur esnext es6now jstransform
|
||||
node node_modules/matcha/bin/_matcha
|
||||
|
||||
lint:
|
||||
$(JSHINT_CMD) --reporter node_modules/jshint-stylish/stylish.js lib bin benchmark/index.js
|
||||
$(JSHINT_CMD) --reporter node_modules/jshint-stylish/stylish.js lib bin
|
||||
|
||||
test-clean:
|
||||
rm -rf test/tmp
|
||||
@@ -41,14 +37,23 @@ test: lint
|
||||
$(MOCHA_CMD)
|
||||
make test-clean
|
||||
|
||||
test-simple:
|
||||
# excludes test262
|
||||
export SIMPLE_6TO5_TESTS=1
|
||||
make test
|
||||
|
||||
test-all:
|
||||
# includes traceur, esnext, regenerator
|
||||
export ALL_6TO5_TESTS=1
|
||||
make test
|
||||
|
||||
test-cov:
|
||||
export SIMPLE_6TO5_TESTS=1
|
||||
rm -rf coverage
|
||||
node $(ISTANBUL_CMD) $(MOCHA_CMD) --
|
||||
|
||||
test-spec:
|
||||
node $(ISTANBUL_CMD) $(MOCHA_CMD) -- --reporter spec
|
||||
|
||||
test-travis: test-spec
|
||||
test-travis: bootstrap
|
||||
node $(ISTANBUL_CMD) $(MOCHA_CMD) --
|
||||
if test -n "$$CODECLIMATE_REPO_TOKEN"; then codeclimate < coverage/lcov.info; fi
|
||||
|
||||
test-browser:
|
||||
@@ -66,6 +71,9 @@ publish:
|
||||
|
||||
make test
|
||||
|
||||
read -p "Version: " version; \
|
||||
npm version $$version --message "v%s"
|
||||
|
||||
make build
|
||||
cp dist/6to5.min.js browser.js
|
||||
cp dist/polyfill.min.js browser-polyfill.js
|
||||
@@ -74,12 +82,21 @@ publish:
|
||||
node bin/cache-templates
|
||||
test -f templates.json
|
||||
|
||||
read -p "Version: " version; \
|
||||
npm version $$version --message "v%s"
|
||||
npm publish
|
||||
|
||||
git push --follow-tags
|
||||
|
||||
# generate
|
||||
bin/generate-core-package-json >package2.json
|
||||
mv package.json .package.json
|
||||
mv package2.json package.json
|
||||
|
||||
npm publish
|
||||
|
||||
# restore
|
||||
rm -rf package.json
|
||||
mv .package.json package.json
|
||||
|
||||
rm -rf templates.json browser.js runtime.js browser-polyfill.js
|
||||
|
||||
bootstrap:
|
||||
|
||||
6
NOTES.md
6
NOTES.md
@@ -1,8 +1,12 @@
|
||||
# Notes
|
||||
|
||||
* Wildcard exports/imports wont normalise if `export default` is a non-object.
|
||||
* Wildcard exports/imports wont normalise if `export default` is a non-object. See [#224](https://github.com/6to5/6to5/issues/224).
|
||||
|
||||
## 3.0.0 breaking changes
|
||||
|
||||
* Remove `allowImportExportEverywhere` option from acorn.
|
||||
* Remove this shorthand from playground.
|
||||
* Remove `super()` inside non-constructors - add descriptive error message.
|
||||
* Split up ES5 getter/setter transforming and ES6 property methods into separate transformers.
|
||||
* Add autoindentation.
|
||||
* Move `super` transformation from classes into a separate transformer that also supports object expressions.
|
||||
|
||||
@@ -1,99 +0,0 @@
|
||||
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
||||
var obj = {};
|
||||
var foo = "foo";
|
||||
var bar = "bar";
|
||||
|
||||
// constants
|
||||
const MULTIPLIER = 5;
|
||||
|
||||
// classes
|
||||
class Foo {
|
||||
constructor() {
|
||||
this.foo = "bar";
|
||||
}
|
||||
}
|
||||
|
||||
class Bar extends Foo {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
// default parameters
|
||||
go(foo = "bar", bar = "foo") {
|
||||
|
||||
}
|
||||
|
||||
// not supported by jstransform
|
||||
//get foo() {
|
||||
// return this._foo;
|
||||
//}
|
||||
//set foo(val) {
|
||||
// this._foo = val + " foo!";
|
||||
//}
|
||||
}
|
||||
|
||||
// arrow functions
|
||||
arr.map(x => x * x);
|
||||
|
||||
// block binding
|
||||
for (let key in arr) {
|
||||
let val = arr[key];
|
||||
console.log(key, val);
|
||||
}
|
||||
|
||||
// computed property names
|
||||
obj = {
|
||||
["foo" + bar]: "foobar"
|
||||
};
|
||||
|
||||
// destructuring
|
||||
var [a, [b], c, d] = ["hello", [", ", "junk"], ["world"]];
|
||||
console.log(a + b + c);
|
||||
|
||||
// array comprehension
|
||||
// [for (i of [1, 2, 3]) i * i]; // not supported by es6now
|
||||
|
||||
// for-of
|
||||
for (var i of [1, 2, 3]) {
|
||||
console.log(i * i);
|
||||
}
|
||||
|
||||
// property method assignment
|
||||
obj = {
|
||||
foo() {
|
||||
return "foobar";
|
||||
},
|
||||
|
||||
get bar() {
|
||||
return this._bar;
|
||||
},
|
||||
|
||||
set bar(val) {
|
||||
this._bar = val;
|
||||
}
|
||||
};
|
||||
|
||||
// property name shorthand
|
||||
function f(x, y) {
|
||||
return { x, y };
|
||||
}
|
||||
|
||||
// rest parameters
|
||||
function printList(name, ...items) {
|
||||
console.log("list %s has the following items", name);
|
||||
items.forEach(function (item) {
|
||||
console.log(item);
|
||||
});
|
||||
}
|
||||
|
||||
// spread
|
||||
function add(x, y) {
|
||||
return x + y;
|
||||
}
|
||||
var numbers = [5, 10];
|
||||
add(...numbers);
|
||||
|
||||
// template literals
|
||||
var x = 5;
|
||||
var y = 10;
|
||||
console.log(`${x} + ${y} = ${x + y}`);
|
||||
@@ -1,168 +0,0 @@
|
||||
Error.stackTraceLimit = Infinity;
|
||||
|
||||
var jsTrans = require("jstransform");
|
||||
var traceur = require("traceur");
|
||||
//var es6tr = require("es6-transpiler");
|
||||
var es6now = require("es6now");
|
||||
//var esnext = require("esnext");
|
||||
var to5 = require("../lib/6to5");
|
||||
|
||||
//var uglify = require("uglify-js");
|
||||
var matcha = require("matcha");
|
||||
var path = require("path");
|
||||
var fs = require("fs");
|
||||
var _ = require("lodash");
|
||||
|
||||
var readResolve = function (filename) {
|
||||
try {
|
||||
filename = require.resolve(filename);
|
||||
} catch (err) {
|
||||
return null;
|
||||
}
|
||||
return fs.readFileSync(filename, "utf8");
|
||||
};
|
||||
|
||||
var getVersion = function (name) {
|
||||
return require(name + "/package.json").version;
|
||||
};
|
||||
|
||||
var jsTransVisitors = [];
|
||||
|
||||
_.each([
|
||||
"arrow-function-visitors", "class-visitors", "destructuring-visitors",
|
||||
"object-concise-method-visitors", "object-short-notation-visitors",
|
||||
"rest-param-visitors", "template-visitors"
|
||||
], function (name) {
|
||||
var mod = require("jstransform/visitors/es6-" + name);
|
||||
jsTransVisitors = jsTransVisitors.concat(mod.visitorList);
|
||||
});
|
||||
|
||||
|
||||
var compilers = {
|
||||
"6to5": {
|
||||
version: getVersion(".."),
|
||||
compile: function (code, filename) {
|
||||
return to5.transform(code, { filename: filename }).code;
|
||||
}
|
||||
},
|
||||
|
||||
traceur: {
|
||||
runtime: readResolve("traceur/bin/traceur-runtime.js"),
|
||||
compile: function (code) {
|
||||
return traceur.compile(code, {
|
||||
modules: "commonjs",
|
||||
experimental: true
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/*esnext: {
|
||||
runtime: readResolve("esnext/node_modules/regenerator/runtime.js") || readResolve("regenerator/runtime.js"),
|
||||
compile: function (code) {
|
||||
return esnext.compile(code).code;
|
||||
}
|
||||
},*/
|
||||
|
||||
es6now: {
|
||||
runtime: readResolve("es6now/runtime/ES6.js"),
|
||||
compile: function (code) {
|
||||
return es6now.translate(code);
|
||||
}
|
||||
},
|
||||
|
||||
/*"es6-transpiler": {
|
||||
compile: function (code) {
|
||||
var result = es6tr.run({ src: code });
|
||||
if (result.errors.length) throw new Error(result.join("; "));
|
||||
return result.src;
|
||||
}
|
||||
},*/
|
||||
|
||||
jstransform: {
|
||||
compile: function (code) {
|
||||
return jsTrans.transform(jsTransVisitors, code).code;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// versions
|
||||
|
||||
//var uglifyTitle = "uglify v" + getVersion("uglify-js");
|
||||
|
||||
_.each(compilers, function (compiler, name) {
|
||||
compiler.title = name + " v" + (compiler.version || getVersion(name));
|
||||
});
|
||||
|
||||
//
|
||||
|
||||
var sizeBenchmark = function (code, loc, name, compiler) {
|
||||
var log = function (output, title) {
|
||||
title = [compiler.title].concat(title || []).join(" + ");
|
||||
|
||||
var text;
|
||||
var color;
|
||||
if (output.stack) {
|
||||
text = "error";
|
||||
color = "red";
|
||||
} else {
|
||||
var kilo = (output.length / 1024).toFixed(2);
|
||||
text = kilo + "KB";
|
||||
color = "cyan";
|
||||
}
|
||||
|
||||
text = matcha.utils.color(matcha.utils.padBefore(text, 22), color);
|
||||
|
||||
console.log(text, matcha.utils.color("» " + title, "gray"));
|
||||
|
||||
if (output.stack) {
|
||||
console.error(output.stack);
|
||||
}
|
||||
};
|
||||
|
||||
var go = function (getOutput, title) {
|
||||
var code;
|
||||
try {
|
||||
code = getOutput();
|
||||
} catch (err) {
|
||||
log(err, title);
|
||||
return;
|
||||
}
|
||||
|
||||
log(code, title);
|
||||
};
|
||||
|
||||
var output;
|
||||
go(function () {
|
||||
return output = compiler.compile(code, loc);
|
||||
});
|
||||
if (!output) return;
|
||||
|
||||
//go(function () {
|
||||
// return uglify.minify(output, { fromString: true }).code;
|
||||
//}, uglifyTitle);
|
||||
};
|
||||
|
||||
//
|
||||
|
||||
_.each(fs.readdirSync(__dirname + "/fixtures"), function (name) {
|
||||
var alias = path.basename(name, path.extname(name));
|
||||
|
||||
suite(alias, function () {
|
||||
set("delay", 0);
|
||||
|
||||
var loc = __dirname + "/fixtures/" + name;
|
||||
var code = fs.readFileSync(loc, "utf8");
|
||||
|
||||
before(function () {
|
||||
_.each(compilers, function (compiler, name) {
|
||||
sizeBenchmark(code, loc, name, compiler);
|
||||
});
|
||||
});
|
||||
|
||||
_.each(compilers, function (compiler) {
|
||||
bench(compiler.title, function () {
|
||||
compiler.compile(code, loc);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -15,14 +15,16 @@ commander.option("-e, --experimental", "Enable experimental support for proposed
|
||||
commander.option("-p, --playground", "Enable playground support");
|
||||
|
||||
commander.option("-m, --modules [modules]", "Module formatter type to use [common]", "common");
|
||||
commander.option("-w, --whitelist [whitelist]", "Whitelist of transformers to ONLY use", util.list);
|
||||
commander.option("-l, --whitelist [whitelist]", "Whitelist of transformers to ONLY use", util.list);
|
||||
commander.option("-b, --blacklist [blacklist]", "Blacklist of transformers to NOT use", util.list);
|
||||
commander.option("-i, --optional [list]", "List of optional transformers to enable", util.list);
|
||||
commander.option("-o, --out-file [out]", "Compile all input files into a single file");
|
||||
commander.option("-d, --out-dir [out]", "Compile an input directory of modules into an output directory");
|
||||
commander.option("-c, --remove-comments", "Remove comments from the compiled code", false);
|
||||
commander.option("-I, --indent [width]", "Indent width [2]", 2);
|
||||
commander.option("-a, --amd-module-ids", "Insert module id in AMD modules", false); // todo: remove in 3.0.0
|
||||
commander.option("-m, --module-ids", "Insert module id in modules", false);
|
||||
commander.option("-R, --react-compat", "Makes the react transformer produce pre-v0.12 code");
|
||||
|
||||
commander.on("--help", function(){
|
||||
var outKeys = function (title, obj) {
|
||||
@@ -108,7 +110,13 @@ exports.opts = {
|
||||
optional: commander.optional,
|
||||
comments: !commander.removeComments,
|
||||
runtime: commander.runtime,
|
||||
modules: commander.modules
|
||||
modules: commander.modules,
|
||||
reactCompat: commander.reactCompat,
|
||||
format: {
|
||||
indent: {
|
||||
style: util.repeat(parseInt(commander.indent))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var fn;
|
||||
|
||||
@@ -10,29 +10,31 @@ var util = require("../lib/6to5/util");
|
||||
var vm = require("vm");
|
||||
var _ = require("lodash");
|
||||
|
||||
commander.option("-e, --eval [script]", "Evaluate script");
|
||||
commander.option("-p, --print", "Evaluate script and print result");
|
||||
commander.option("-i, --ignore [regex]", "Ignore all files that match this regex when using the require hook");
|
||||
commander.option("-x, --extensions [extensions]", "List of extensions to hook into [.es6,.js]");
|
||||
commander.option("-r, --experimental", "Enable experimental support for proposed ES7 features");
|
||||
commander.option("-g, --playground", "Enable playground support");
|
||||
commander.option("-c, --cache", "Cache compiled files and require paths");
|
||||
var program = new commander.Command("6to5-node");
|
||||
|
||||
program.option("-e, --eval [script]", "Evaluate script");
|
||||
program.option("-p, --print", "Evaluate script and print result");
|
||||
program.option("-i, --ignore [regex]", "Ignore all files that match this regex when using the require hook");
|
||||
program.option("-x, --extensions [extensions]", "List of extensions to hook into [.es6,.js]");
|
||||
program.option("-r, --experimental", "Enable experimental support for proposed ES7 features");
|
||||
program.option("-g, --playground", "Enable playground support");
|
||||
program.option("-c, --cache", "Cache compiled files and require paths");
|
||||
|
||||
var pkg = require("../package.json");
|
||||
commander.version(pkg.version);
|
||||
commander.usage("[options] [ -e script | script.js ] [arguments]");
|
||||
commander.parse(process.argv);
|
||||
program.version(pkg.version);
|
||||
program.usage("[options] [ -e script | script.js ] [arguments]");
|
||||
program.parse(process.argv);
|
||||
|
||||
if (commander.cache) roadrunner.load();
|
||||
if (program.cache) roadrunner.load();
|
||||
|
||||
//
|
||||
|
||||
to5.register({
|
||||
experimental: commander.experimental,
|
||||
extensions: commander.extensions,
|
||||
playground: commander.playground,
|
||||
ignore: commander.ignore,
|
||||
cache: commander.cache && roadrunner.get("6to5")
|
||||
experimental: program.experimental,
|
||||
extensions: program.extensions,
|
||||
playground: program.playground,
|
||||
ignore: program.ignore,
|
||||
cache: program.cache && roadrunner.get("6to5")
|
||||
});
|
||||
|
||||
//
|
||||
@@ -41,17 +43,17 @@ var _eval = function (code, filename) {
|
||||
code = to5.transform(code, {
|
||||
filename: filename,
|
||||
blacklist: ["useStrict"],
|
||||
experimental: commander.experimental,
|
||||
playground: commander.playground
|
||||
experimental: program.experimental,
|
||||
playground: program.playground
|
||||
}).code;
|
||||
return vm.runInThisContext(code, filename);
|
||||
};
|
||||
|
||||
if (commander.eval) {
|
||||
var result = _eval(commander.eval, "eval");
|
||||
if (commander.print) console.log(result);
|
||||
if (program.eval) {
|
||||
var result = _eval(program.eval, "eval");
|
||||
if (program.print) console.log(result);
|
||||
} else {
|
||||
if (commander.args.length) {
|
||||
if (program.args.length) {
|
||||
// slice all arguments up to the first filename since they're 6to5 args that we handle
|
||||
var args = process.argv.slice(2);
|
||||
|
||||
@@ -77,7 +79,7 @@ if (commander.eval) {
|
||||
}
|
||||
}
|
||||
|
||||
if (commander.cache) roadrunner.save();
|
||||
if (program.cache) roadrunner.save();
|
||||
|
||||
function replStart() {
|
||||
repl.start({
|
||||
|
||||
11
bin/generate-core-package-json
Executable file
11
bin/generate-core-package-json
Executable file
@@ -0,0 +1,11 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
var pkg = require("../package.json");
|
||||
pkg.name += "-core";
|
||||
delete pkg.dependencies.chokidar;
|
||||
delete pkg.optionalDependencies;
|
||||
delete pkg.devDependencies;
|
||||
delete pkg.preferGlobal;
|
||||
delete pkg.scripts;
|
||||
delete pkg.bin;
|
||||
console.log(JSON.stringify(pkg, null, " "));
|
||||
@@ -1,89 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: Caveats
|
||||
description: Just some things to keep in mind when using 6to5.
|
||||
permalink: /docs/caveats/
|
||||
redirect_from: /caveats.html
|
||||
---
|
||||
|
||||
## Polyfills
|
||||
|
||||
In order for certain features to work they require certain polyfills. You can
|
||||
satisfy **all** 6to5 feature requirements by using the included
|
||||
[polyfill](polyfill.md).
|
||||
|
||||
You may alternatively selectively include what you need:
|
||||
|
||||
| Feature | Requirements |
|
||||
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
|
||||
| Abstract References | [experimental](experimental.md), `Symbol` |
|
||||
| Array destructuring | `Array.from` |
|
||||
| Async functions, Generators | [experimental](experimental.md), [regenerator runtime](https://github.com/facebook/regenerator/blob/master/runtime.js) |
|
||||
| Comprehensions | [experimental](experimental.md), `Array.from` |
|
||||
| For Of | `Symbol`, `prototype[Symbol.iterator]` |
|
||||
| Modules | `Object.assign`* |
|
||||
| Object spread/rest | [experimental](experimental.md), `Object.assign` |
|
||||
| Spread | `Array.from` |
|
||||
|
||||
*Only required for exporting a non-function `default` with additional `export`s.
|
||||
|
||||
## ES5
|
||||
|
||||
Since 6to5 assumes that your code will be ran in an ES5 environment it uses ES5
|
||||
functions. So if you're using an environment that has limited or no support for
|
||||
ES5 such as lower versions of IE then using the
|
||||
[es5-shim](https://github.com/es-shims/es5-shim) along with the
|
||||
[6to5 polyfill](polyfill.md) will add support for these methods.
|
||||
|
||||
## Internet Explorer
|
||||
|
||||
### Classes (10 and below)
|
||||
|
||||
If you're inheriting from a class then static properties are inherited from it
|
||||
via [\_\_proto\_\_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto),
|
||||
this is widely supported but you may run into problems with much older browsers.
|
||||
|
||||
**NOTE:** `__proto__` is not supported on IE <= 10 so static properties
|
||||
**will not** be inherited.
|
||||
|
||||
You can use the `protoToAssign` optional transformer that will transform all
|
||||
`__proto__` assignments to a method that will shallowly copy it over all
|
||||
properties.
|
||||
|
||||
```javascript
|
||||
require("6to5").transform("code", { optional: ["protoToAssign"] });
|
||||
```
|
||||
|
||||
```sh
|
||||
$ 6to5 --optional protoToAssign script.js
|
||||
```
|
||||
|
||||
This means that the following **will** work:
|
||||
|
||||
```javascript
|
||||
var foo = { a: 1 };
|
||||
var bar = { b: 2 };
|
||||
bar.__proto__ = foo;
|
||||
bar.a; // 1
|
||||
bar.b; // 2
|
||||
```
|
||||
|
||||
however the following **will not**:
|
||||
|
||||
```javascript
|
||||
var foo = { a: 1 };
|
||||
var bar = { b: 2 };
|
||||
bar.__proto__ = foo;
|
||||
bar.a; // 1
|
||||
foo.a = 2;
|
||||
bar.a; // 1 - should be 2 but remember that nothing is bound and it's a straight copy
|
||||
```
|
||||
|
||||
### Getters/setters (8 and below)
|
||||
|
||||
In IE8 `Object.defineProperty` can only be used on DOM objects. This is
|
||||
unfortunate as it's required to set getters and setters. Due to this if
|
||||
you plan on supporting IE8 or below then the user of getters and setters
|
||||
isn't recommended.
|
||||
|
||||
**Reference**: [MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Internet_Explorer_8_specific_notes).
|
||||
143
doc/compare.md
143
doc/compare.md
@@ -1,143 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: Compare
|
||||
description: Differences between 6to5 and other ES6 transpilers.
|
||||
permalink: /docs/compare/
|
||||
redirect_from: /differences.html
|
||||
---
|
||||
|
||||
## Differences
|
||||
|
||||
### Readable code
|
||||
|
||||
The fundamental concept behind 6to5 is that the generated code must be close as
|
||||
possible to the original, retaining all the same formatting and readability.
|
||||
|
||||
Many other transpilers are just concerned with making the code work while 6to5
|
||||
is concerned with making sure it works **and** is readable at the same time.
|
||||
|
||||
For example, given the following array comprehension:
|
||||
|
||||
```js
|
||||
var seattlers = [for (c of customers) if (c.city == "Seattle") { name: c.name, age: c.age }];
|
||||
```
|
||||
|
||||
is generated to the following with 6to5:
|
||||
|
||||
```js
|
||||
var seattlers = Array.from(customers).filter(function (c) {
|
||||
return c.city == "Seattle";
|
||||
}).map(function (c) {
|
||||
return {
|
||||
name: c.name,
|
||||
age: c.age
|
||||
};
|
||||
});
|
||||
```
|
||||
|
||||
The following is what Traceur generates:
|
||||
|
||||
```js
|
||||
var seattlers = (function() {
|
||||
var c;
|
||||
var $__20 = 0,
|
||||
$__21 = [];
|
||||
for (var $__22 = customers[$traceurRuntime.toProperty(Symbol.iterator)](),
|
||||
$__23; !($__23 = $__22.next()).done; ) {
|
||||
c = $__23.value;
|
||||
if (c.city == "Seattle")
|
||||
$traceurRuntime.setProperty($__21, $__20++, {
|
||||
name: c.name,
|
||||
age: c.age
|
||||
});
|
||||
}
|
||||
return $__21;
|
||||
}());
|
||||
```
|
||||
|
||||
As you can tell, it's not very pretty. Instead of mapping directly to a runtime,
|
||||
like other transpilers, 6to5 maps directly to the equivalent ES5.
|
||||
|
||||
Sometimes there are little inline functions that 6to5 needs. These are
|
||||
placed at the top of your file much like coffee-script does. If these
|
||||
bother you then you can use the [optional runtime](optional-runtime.md).
|
||||
We promise that these inline functions will never be significant and will
|
||||
always be used as little as possible.
|
||||
|
||||
### Static analysis
|
||||
|
||||
6to5 uses a lot of static analysis to simplify code as much as possible.
|
||||
Not many other transpilers do this, and those that do don't do it nearly
|
||||
as much as 6to5. This process is pretty intensive but it leads to higher
|
||||
quality code.
|
||||
|
||||
### Spec compliancy
|
||||
|
||||
6to5 prides itself on
|
||||
[spec compliancy](https://kangax.github.io/compat-table/es6/). We have
|
||||
excellent support for edgecases, something that many other transpilers
|
||||
suffer from, including Traceur. When you use 6to5 you can be confident
|
||||
that when you turn it off and use your code in a full ES6 environment
|
||||
**it'll just work**.
|
||||
|
||||
## Comparison to other transpilers
|
||||
|
||||
### Features
|
||||
|
||||
| | 6to5 | Traceur | es6-transpiler | es6now | jstransform |
|
||||
| ---------------------------- | ---- | ------- | -------------- | ------ | ----------- |
|
||||
| Source maps | ✓ | ✓ | ✓ | | ✓ |
|
||||
| No compiler global pollution | ✓ | | ✓ | | ✓ |
|
||||
| Optional runtime | ✓ | | ✓ | | ✓ |
|
||||
| Browser compiler | ✓ | ✓ | | | |
|
||||
|
||||
### Language Support
|
||||
|
||||
| | 6to5 | Traceur | es6-transpiler | es6now | jstransform |
|
||||
| ---------------------------- | ---- | ------- | -------------- | ------ | ----------- |
|
||||
| Abstract references | ✓ | | | | |
|
||||
| Array comprehension | ✓ | ✓ | ✓ | | |
|
||||
| Arrow functions | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||
| Async functions | ✓ | ✓ | | | |
|
||||
| Async generator functions | ✓ | ✓ | | | |
|
||||
| Classes | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||
| Computed property names | ✓ | ✓ | ✓ | ✓ | |
|
||||
| Constants | ✓ | ✓ | ✓ | | |
|
||||
| Default parameters | ✓ | ✓ | ✓ | ✓ | |
|
||||
| Destructuring | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||
| Exponentiation operator | ✓ | ✓ | | | |
|
||||
| Flow types | ✓ | | | | ✓ |
|
||||
| For-of | ✓ | ✓ | ✓ | ✓ | |
|
||||
| Generators | ✓ | ✓ | | | |
|
||||
| Generator comprehension | ✓ | ✓ | | | |
|
||||
| JSX | ✓ | | | | |
|
||||
| Let scoping | ✓ | ✓ | ✓ | | |
|
||||
| Modules | ✓ | ✓ | | ✓ | |
|
||||
| Object rest/spread | ✓ | | | | ✓ |
|
||||
| Property method assignment | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||
| Property name shorthand | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||
| Rest parameters | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||
| React | ✓ | | | | |
|
||||
| Spread | ✓ | ✓ | ✓ | ✓ | |
|
||||
| Template literals | ✓ | ✓ | ✓ | ✓ | ✓ |
|
||||
| Unicode regex | ✓ | ✓ | ✓ | | |
|
||||
|
||||
### [Traceur](https://github.com/google/traceur-compiler)
|
||||
|
||||
Traceur requires quite a bulky runtime (~75KB) and produces quite verbose code.
|
||||
While this can be trimmed down by selectively building the runtime, it's an
|
||||
unnecessary step when a large runtime can be eliminated entirely.
|
||||
|
||||
### [es6now](https://github.com/zenparsing/es6now)
|
||||
|
||||
es6now doesn't output sourcemaps. This is cited as a positive as line-to-line
|
||||
mapping is the goal. This however obviously doesn't retain column mapping
|
||||
resulting in the output code not being very pleasant.
|
||||
|
||||
### [es6-transpiler](https://github.com/termi/es6-transpiler)
|
||||
|
||||
The es6-transpiler compiler requires shims to operate which pollutes the global
|
||||
scope resulting in possible collisions.
|
||||
|
||||
es6-transpiler maps line-by-line, just like es6now, this results in the same
|
||||
issues such as lack of column information and unpleasant code output.
|
||||
1
doc/index.md
Normal file
1
doc/index.md
Normal file
@@ -0,0 +1 @@
|
||||
See [6to5.github.io/docs](https://github.com/6to5/6to5.github.io/tree/master/docs).
|
||||
708
doc/setup.md
708
doc/setup.md
@@ -1,708 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: Setup
|
||||
description: Guides on how to setup 6to5 in whatever environment you might be working in.
|
||||
permalink: /docs/setup/
|
||||
redirect_from: /plugins.html
|
||||
---
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<h4>Find your guide</h4>
|
||||
<p>
|
||||
It doesn't matter if you're using Node.js or Rails, Gulp or Grunt, there's likely a guide on
|
||||
this page to help guide you. Go ahead and <span class="label label-info">⌘ + F</span>
|
||||
whatever you're looking for. If it doesn't happen to be on this page you might want to stop by
|
||||
our <a href="https://gitter.im/6to5/6to5">support chat</a>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
## Node.js
|
||||
|
||||
### CLI
|
||||
|
||||
**Install**
|
||||
|
||||
```sh
|
||||
$ npm install --global 6to5
|
||||
```
|
||||
|
||||
**Usage**
|
||||
|
||||
```sh
|
||||
$ 6to5 script.js
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
For full documentation on the 6to5 CLI see the
|
||||
<a href="/docs/usage/cli/">usage docs</a>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
### Require Hook
|
||||
|
||||
**Install**
|
||||
|
||||
```sh
|
||||
$ npm install 6to5
|
||||
```
|
||||
|
||||
**Usage**
|
||||
|
||||
All subsequent files required by node with the extensions `.es6` and `.js` will
|
||||
be transformed by 6to5. The polyfill specified in [Polyfill](polyfill.md) is
|
||||
also required.
|
||||
|
||||
```javascript
|
||||
require('6to5/register');
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
For full documentation on the 6to5 require hook see the
|
||||
<a href="/docs/usage/require/">usage docs</a>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
## Rails
|
||||
|
||||
### Sprockets
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>sprockets-es6</strong>'s
|
||||
<a href="https://github.com/josh/sprockets-es6">repo</a> for more info. If
|
||||
you find any bugs please
|
||||
<a href="https://github.com/josh/sprockets-es6/issues">report them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```sh
|
||||
$ gem install sprockets-es6
|
||||
```
|
||||
|
||||
**Usage**
|
||||
|
||||
```rb
|
||||
# Gemfile
|
||||
gem 'sprockets'
|
||||
gem 'sprockets-es6'
|
||||
```
|
||||
|
||||
```rb
|
||||
require 'sprockets/es6'
|
||||
```
|
||||
|
||||
## Build Systems
|
||||
|
||||
### Brocolli
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>broccoli-6to5-transpiler</strong>'s
|
||||
<a href="https://github.com/6to5/broccoli-6to5-transpiler">repo</a> for more
|
||||
info. If you find any bugs please
|
||||
<a href="https://github.com/6to5/broccoli-6to5-transpiler/issues">report
|
||||
them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```sh
|
||||
$ npm install --save-dev broccoli-6to5-transpiler
|
||||
```
|
||||
|
||||
**Usage**
|
||||
|
||||
```js
|
||||
var to5Transpiler = require('broccoli-6to5-transpiler');
|
||||
var scriptTree = to5Transpiler(inputTree, options);
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-warning">
|
||||
<h4>Source maps</h4>
|
||||
<p>
|
||||
Currently this plugin only support inline source maps. If you need separate
|
||||
source map feature, we welcome you to submit a pull request.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
### Browserify
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>6to5ify</strong>'s
|
||||
<a href="https://github.com/6to5/6to5ify">repo</a> for more info. If you
|
||||
find any bugs please
|
||||
<a href="https://github.com/6to5/6to5ify/issues">report them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```sh
|
||||
$ npm install --save-dev 6to5ify
|
||||
```
|
||||
|
||||
**Usage via CLI**
|
||||
|
||||
```sh
|
||||
$ browserify script.js -t 6to5ify --outfile bundle.js
|
||||
```
|
||||
|
||||
**Usage via Node.js**
|
||||
|
||||
```js
|
||||
browserify({ debug: true })
|
||||
.transform(to5ify);
|
||||
```
|
||||
|
||||
Or a more complete example:
|
||||
|
||||
```js
|
||||
var fs = require('fs');
|
||||
var browserify = require('browserify');
|
||||
var to5ify = require('6to5ify');
|
||||
|
||||
browserify({ debug: true })
|
||||
.transform(to5ify)
|
||||
.require('./script.js', { entry: true })
|
||||
.bundle()
|
||||
.on('error', function (err) { console.log('Error: ' + err.message); })
|
||||
.pipe(fs.createWriteStream("bundle.js"));
|
||||
```
|
||||
**Passing Options**
|
||||
|
||||
```sh
|
||||
$ browserify -d -e script.js -t [ 6to5ify --blacklist generators ]
|
||||
```
|
||||
|
||||
```js
|
||||
browserify().transform(to5ify.configure({
|
||||
blacklist: ['generators']
|
||||
}))
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<h4>More info</h4>
|
||||
<p>
|
||||
For more information see the
|
||||
<a href="https://github.com/6to5/6to5ify">6to5ify README</a>
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
### Brunch
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>6to5-brunch</strong>'s
|
||||
<a href="https://github.com/6to5/6to5-brunch">repo</a> for more info. If you
|
||||
find any bugs please
|
||||
<a href="https://github.com/6to5/6to5-brunch/issues">report them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```sh
|
||||
$ npm install --save-dev 6to5-brunch
|
||||
```
|
||||
|
||||
**Configuring**
|
||||
|
||||
Set 6to5 options in your brunch config (such as `brunch-config.coffee`) except
|
||||
for `filename` and `sourceMap` which are handled internally.
|
||||
|
||||
```coffee
|
||||
plugins:
|
||||
ES6to5:
|
||||
whitelist: ['arrowFunctions']
|
||||
format:
|
||||
semicolons: false
|
||||
```
|
||||
|
||||
### Duo
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>duo-6to5</strong>'s
|
||||
<a href="https://github.com/6to5/duo-6to5">repo</a> for more info. If you
|
||||
find any bugs please
|
||||
<a href="https://github.com/6to5/duo-6to5/issues">report them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```sh
|
||||
$ npm install --save-dev duo-6to5
|
||||
```
|
||||
|
||||
**Usage via CLI**
|
||||
|
||||
```sh
|
||||
$ duo --use duo-6to5
|
||||
```
|
||||
|
||||
**Usage via Node.js**
|
||||
|
||||
```js
|
||||
Duo(root)
|
||||
.entry(entry)
|
||||
.use(to5)
|
||||
.run(fn);
|
||||
```
|
||||
|
||||
### Gobble
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>gobble-6to5</strong>'s
|
||||
<a href="https://github.com/6to5/gobble-6to5">repo</a> for more info. If you
|
||||
find any bugs please
|
||||
<a href="https://github.com/6to5/gobble-6to5/issues">report them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```sh
|
||||
$ npm install --save-dev gobble-6to5
|
||||
```
|
||||
|
||||
**Usage**
|
||||
|
||||
The `options` argument, if specified, is passed to 6to5.
|
||||
|
||||
```
|
||||
var gobble = require('gobble');
|
||||
module.exports = gobble('src').transform('6to5', options);
|
||||
```
|
||||
|
||||
**Source maps**
|
||||
|
||||
Sourcemaps are created by default (all the relevant information is filled in by
|
||||
Gobble, you don't need to specify `sourceMapName` options etc). If you don't
|
||||
want that, pass `sourceMap: false`.
|
||||
|
||||
### Grunt
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>grunt-6to5</strong>'s
|
||||
<a href="https://github.com/6to5/grunt-6to5">repo</a> for more info. If you
|
||||
find any bugs please
|
||||
<a href="https://github.com/6to5/grunt-6to5/issues">report them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```sh
|
||||
$ npm install --save-dev grunt-6to5
|
||||
```
|
||||
|
||||
**Usage**
|
||||
|
||||
```js
|
||||
require('load-grunt-tasks')(grunt); // npm install --save-dev load-grunt-tasks
|
||||
|
||||
grunt.initConfig({
|
||||
'6to5': {
|
||||
options: {
|
||||
sourceMap: true
|
||||
},
|
||||
dist: {
|
||||
files: {
|
||||
'dist/app.js': 'src/app.js'
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
grunt.registerTask('default', ['6to5']);
|
||||
```
|
||||
|
||||
### Gulp
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>gulp-6to5</strong>'s
|
||||
<a href="https://github.com/6to5/gulp-6to5">repo</a> for more info. If you
|
||||
find any bugs please
|
||||
<a href="https://github.com/6to5/gulp-6to5/issues">report them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```sh
|
||||
$ npm install --save-dev gulp-6to5
|
||||
```
|
||||
|
||||
**Usage**
|
||||
|
||||
```js
|
||||
var gulp = require('gulp');
|
||||
var to5 = require('gulp-6to5');
|
||||
|
||||
gulp.task('default', function () {
|
||||
return gulp.src('src/app.js')
|
||||
.pipe(to5())
|
||||
.pipe(gulp.dest('dist'));
|
||||
});
|
||||
```
|
||||
|
||||
**Source maps**
|
||||
|
||||
Use [gulp-sourcemaps](https://github.com/floridoo/gulp-sourcemaps) like this:
|
||||
|
||||
```js
|
||||
var gulp = require('gulp');
|
||||
var sourcemaps = require('gulp-sourcemaps');
|
||||
var to5 = require('gulp-6to5');
|
||||
var concat = require('gulp-concat');
|
||||
|
||||
gulp.task('default', function () {
|
||||
return gulp.src('src/**/*.js')
|
||||
.pipe(sourcemaps.init())
|
||||
.pipe(to5())
|
||||
.pipe(concat('all.js'))
|
||||
.pipe(sourcemaps.write('.'))
|
||||
.pipe(gulp.dest('dist'));
|
||||
});
|
||||
```
|
||||
|
||||
### Webpack
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>6to5-loader</strong>'s
|
||||
<a href="https://github.com/6to5/6to5-loader">repo</a> for more info. If you
|
||||
find any bugs please
|
||||
<a href="https://github.com/6to5/6to5-loader/issues">report them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```sh
|
||||
$ npm install --save-dev 6to5-loader
|
||||
```
|
||||
|
||||
**Usage via loader**
|
||||
|
||||
```js
|
||||
import Animal from '6to5!./Animal.js';
|
||||
|
||||
class Person extends Animal {
|
||||
constructor(arg='default') {
|
||||
this.eat = 'Happy Meal';
|
||||
}
|
||||
}
|
||||
|
||||
export default Person;
|
||||
```
|
||||
```js
|
||||
var Person = require('6to5!./Person.js').default;
|
||||
new Person();
|
||||
```
|
||||
|
||||
**Usage via config**
|
||||
|
||||
```js
|
||||
module: {
|
||||
loaders: [
|
||||
{ test: /\.js$/, exclude: /node_modules/, loader: '6to5-loader'}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
and then import normally:
|
||||
|
||||
```js
|
||||
import Person from './Person.js';
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-warning">
|
||||
<h4>Troubleshooting</h4>
|
||||
<p>
|
||||
For additional information on how to troubleshoot **6to5-loader** please
|
||||
see the
|
||||
<a href="https://github.com/6to5/6to5-loader#troubleshooting">README</a>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
## Misc
|
||||
|
||||
### Connect
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>6to5-connect</strong>'s
|
||||
<a href="https://github.com/6to5/6to5-connect">repo</a> for more info. If
|
||||
you find any bugs please
|
||||
<a href="https://github.com/6to5/6to5-connect/issues">report them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```js
|
||||
$ npm install 6to5-connect
|
||||
```
|
||||
|
||||
**Usage**
|
||||
|
||||
```js
|
||||
var to5Middleware = require('6to5-connect');
|
||||
|
||||
app.use(to5Middleware({
|
||||
options: {
|
||||
// options to use when transforming files
|
||||
},
|
||||
src: 'assets',
|
||||
dest: 'cache'
|
||||
}));
|
||||
|
||||
app.use(connect.static('cache'));
|
||||
```
|
||||
|
||||
### Jade
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>jade-6to5</strong>'s
|
||||
<a href="https://github.com/6to5/jade-6to5">repo</a> for more info. If you
|
||||
find any bugs please
|
||||
<a href="https://github.com/6to5/jade-6to5/issues">report them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```js
|
||||
$ npm install jade-6to5
|
||||
```
|
||||
|
||||
**Usage**
|
||||
|
||||
```js
|
||||
var jade = require('jade');
|
||||
var to5 = require('jade-6to5');
|
||||
|
||||
jade.filters.to5 = to5({});
|
||||
```
|
||||
|
||||
OR
|
||||
|
||||
```js
|
||||
var jade = require('jade');
|
||||
var to5 = require('jade-6to5');
|
||||
|
||||
jade = to5({}, jade);
|
||||
```
|
||||
|
||||
Now you can use ES6 in your jade templates as following.
|
||||
|
||||
```jade
|
||||
script
|
||||
:to5
|
||||
console.log('Hello World !!!');
|
||||
class Person {
|
||||
constructor(name) {
|
||||
this.name = name;
|
||||
}
|
||||
sayName(){
|
||||
console.log(`Hello, my name is ${this.name}`);
|
||||
}
|
||||
}
|
||||
var person = new Person('Apoxx');
|
||||
person.sayName();
|
||||
```
|
||||
|
||||
### Jest
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>6to5-jest</strong>'s
|
||||
<a href="https://github.com/6to5/6to5-jest">repo</a> for more info. If you
|
||||
find any bugs please
|
||||
<a href="https://github.com/6to5/6to5-jest/issues">report them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```sh
|
||||
$ npm install --save-dev 6to5-jest
|
||||
```
|
||||
|
||||
**Usage**
|
||||
|
||||
In your `package.json` file please make the following changes:
|
||||
|
||||
```
|
||||
{
|
||||
"dependencies": {
|
||||
"6to5-jest": "*",
|
||||
"jest": "*"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "jest"
|
||||
},
|
||||
"jest": {
|
||||
"scriptPreprocessor": "<rootDir>/node_modules/6to5-jest",
|
||||
"testFileExtensions": ["es6", "js"],
|
||||
"moduleFileExtensions": ["js", "json", "es6"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Karma
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>karma-6to5-preprocessor</strong>'s
|
||||
<a href="https://github.com/6to5/karma-6to5-preprocessor">repo</a> for more
|
||||
info. If you find any bugs please
|
||||
<a href="https://github.com/6to5/karma-6to5-preprocessor/issues">report them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```js
|
||||
npm install --save-dev karma-6to5-preprocessor
|
||||
```
|
||||
|
||||
**Usage**
|
||||
|
||||
See 6to5 options for more details.
|
||||
|
||||
Given `options` properties are passed to 6to5 with no change except:
|
||||
|
||||
- `filename`
|
||||
- `sourceMapName`
|
||||
- `sourceFileName`
|
||||
|
||||
Because they should differ from file to file, corresponding configuration
|
||||
functions are available.
|
||||
|
||||
For example, inline sourcemap configuration would look like the following.
|
||||
|
||||
```js
|
||||
module.exports = function(config) {
|
||||
config.set({
|
||||
files: [
|
||||
'src/**/*.js',
|
||||
'test/**/*.js'
|
||||
],
|
||||
preprocessors: {
|
||||
'src/**/*.js': ['6to5'],
|
||||
'test/**/*.js': ['6to5']
|
||||
},
|
||||
'6to5Preprocessor': {
|
||||
options: {
|
||||
sourceMap: 'inline'
|
||||
},
|
||||
filename: function(file) {
|
||||
return file.originalPath.replace(/\.js$/, '.es5.js');
|
||||
},
|
||||
sourceFileName: function(file) {
|
||||
return file.originalPath;
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
### Mocha
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<p>
|
||||
See <strong>6to5-mocha</strong>'s
|
||||
<a href="https://github.com/6to5/6to5-mocha">repo</a> for more info. If you
|
||||
find any bugs please
|
||||
<a href="https://github.com/6to5/6to5-mocha/issues">report them</a>.
|
||||
</p>
|
||||
<p>
|
||||
<em>Issues with the output should be reported on the 6to5
|
||||
<a href="https://github.com/6to5/6to5/issues">issue tracker</a></em>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
**Install**
|
||||
|
||||
```sh
|
||||
$ npm install --save-dev 6to5
|
||||
```
|
||||
|
||||
**Usage**
|
||||
|
||||
```js
|
||||
{
|
||||
"scripts": {
|
||||
"test": "mocha --require 6to5/register"
|
||||
},
|
||||
"devDependencies": {
|
||||
"6to5": "*",
|
||||
"mocha": "*"
|
||||
}
|
||||
}
|
||||
```
|
||||
771
doc/tour.md
771
doc/tour.md
@@ -1,771 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: Tour
|
||||
description: A detailed overview of ECMAScript 6 features.
|
||||
permalink: /docs/tour/
|
||||
redirect_from: /features.html
|
||||
---
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<h4>es6features</h4>
|
||||
<p>
|
||||
This document is taken from Luke Hoban's excellent
|
||||
<a href="http://git.io/es6features">es6features</a> repo. Go give it a star
|
||||
on GitHub!
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<h4>REPL</h4>
|
||||
<p>
|
||||
Be sure to try these features out in the online
|
||||
<a href="repl.html">REPL</a>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
## Introduction
|
||||
|
||||
> ECMAScript 6 is the upcoming version of the ECMAScript standard. This
|
||||
standard is targeting ratification in June 2015. ES6 is a significant update to
|
||||
the language, and the first update to the language since ES5 was standardized in
|
||||
2009. Implementation of these features in major JavaScript engines is
|
||||
[underway now](http://kangax.github.io/es5-compat-table/es6/).
|
||||
|
||||
See the [draft ES6 standard](https://people.mozilla.org/~jorendorff/es6-draft.html)
|
||||
for full specification of the ECMAScript 6 language.
|
||||
|
||||
## ECMAScript 6 Features
|
||||
|
||||
### Arrows
|
||||
|
||||
Arrows are a function shorthand using the `=>` syntax. They are syntactically
|
||||
similar to the related feature in C#, Java 8 and CoffeeScript. They support
|
||||
both expression and statement bodies. Unlike functions, arrows share the same
|
||||
lexical `this` as their surrounding code.
|
||||
|
||||
```js
|
||||
// Expression bodies
|
||||
var odds = evens.map(v => v + 1);
|
||||
var nums = evens.map((v, i) => v + i);
|
||||
|
||||
// Statement bodies
|
||||
nums.forEach(v => {
|
||||
if (v % 5 === 0)
|
||||
fives.push(v);
|
||||
});
|
||||
|
||||
// Lexical this
|
||||
var bob = {
|
||||
_name: "Bob",
|
||||
_friends: [],
|
||||
printFriends() {
|
||||
this._friends.forEach(f =>
|
||||
console.log(this._name + " knows " + f));
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Classes
|
||||
|
||||
ES6 classes are a simple sugar over the prototype-based OO pattern. Having a
|
||||
single convenient declarative form makes class patterns easier to use, and
|
||||
encourages interoperability. Classes support prototype-based inheritance, super
|
||||
calls, instance and static methods and constructors.
|
||||
|
||||
```js
|
||||
class SkinnedMesh extends THREE.Mesh {
|
||||
constructor(geometry, materials) {
|
||||
super(geometry, materials);
|
||||
|
||||
this.idMatrix = SkinnedMesh.defaultMatrix();
|
||||
this.bones = [];
|
||||
this.boneMatrices = [];
|
||||
//...
|
||||
}
|
||||
update(camera) {
|
||||
//...
|
||||
super.update();
|
||||
}
|
||||
static defaultMatrix() {
|
||||
return new THREE.Matrix4();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Enhanced Object Literals
|
||||
|
||||
Object literals are extended to support setting the prototype at construction,
|
||||
shorthand for `foo: foo` assignments, defining methods and making super calls.
|
||||
Together, these also bring object literals and class declarations closer
|
||||
together, and let object-based design benefit from some of the same
|
||||
conveniences.
|
||||
|
||||
```js
|
||||
var obj = {
|
||||
// __proto__
|
||||
__proto__: theProtoObj,
|
||||
// Shorthand for ‘handler: handler’
|
||||
handler,
|
||||
// Methods
|
||||
toString() {
|
||||
// Super calls
|
||||
return "d " + super.toString();
|
||||
},
|
||||
// Computed (dynamic) property names
|
||||
[ 'prop_' + (() => 42)() ]: 42
|
||||
};
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-warning">
|
||||
<p>
|
||||
<code>__proto__</code> support comes from the JavaScript engine running
|
||||
your program. Although most support the now standard property,
|
||||
<a href="http://kangax.github.io/compat-table/es6/#__proto___in_object_literals">some do not</a>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
### Template Strings
|
||||
|
||||
Template strings provide syntactic sugar for constructing strings. This is
|
||||
similar to string interpolation features in Perl, Python and more. Optionally, a
|
||||
tag can be added to allow the string construction to be customized, avoiding
|
||||
injection attacks or constructing higher level data structures from string
|
||||
contents.
|
||||
|
||||
```js
|
||||
// Basic literal string creation
|
||||
`In JavaScript '\n' is a line-feed.`
|
||||
|
||||
// Multiline strings
|
||||
`In JavaScript this is
|
||||
not legal.`
|
||||
|
||||
// Construct a DOM query
|
||||
var name = "Bob", time = "today";
|
||||
`Hello ${name}, how are you ${time}?`
|
||||
|
||||
// Construct an HTTP request prefix is used to interpret the replacements and construction
|
||||
GET`http://foo.org/bar?a=${a}&b=${b}
|
||||
Content-Type: application/json
|
||||
X-Credentials: ${credentials}
|
||||
{ "foo": ${foo},
|
||||
"bar": ${bar}}`(myOnReadyStateChangeHandler);
|
||||
```
|
||||
|
||||
### Destructuring
|
||||
|
||||
Destructuring allows binding using pattern matching, with support for matching
|
||||
arrays and objects. Destructuring is fail-soft, similar to standard object
|
||||
lookup `foo["bar"]`, producing `undefined` values when not found.
|
||||
|
||||
```js
|
||||
// list matching
|
||||
var [a, , b] = [1,2,3];
|
||||
|
||||
// object matching
|
||||
var { op: a, lhs: { op: b }, rhs: c }
|
||||
= getASTNode()
|
||||
|
||||
// object matching shorthand
|
||||
// binds `op`, `lhs` and `rhs` in scope
|
||||
var {op, lhs, rhs} = getASTNode()
|
||||
|
||||
// Can be used in parameter position
|
||||
function g({name: x}) {
|
||||
console.log(x);
|
||||
}
|
||||
g({name: 5})
|
||||
|
||||
// Fail-soft destructuring
|
||||
var [a] = [];
|
||||
a === undefined;
|
||||
|
||||
// Fail-soft destructuring with defaults
|
||||
var [a = 1] = [];
|
||||
a === 1;
|
||||
```
|
||||
|
||||
### Default + Rest + Spread
|
||||
|
||||
Callee-evaluated default parameter values. Turn an array into consecutive
|
||||
arguments in a function call. Bind trailing parameters to an array. Rest
|
||||
replaces the need for `arguments` and addresses common cases more directly.
|
||||
|
||||
```js
|
||||
function f(x, y=12) {
|
||||
// y is 12 if not passed (or passed as undefined)
|
||||
return x + y;
|
||||
}
|
||||
f(3) == 15
|
||||
```
|
||||
```js
|
||||
function f(x, ...y) {
|
||||
// y is an Array
|
||||
return x * y.length;
|
||||
}
|
||||
f(3, "hello", true) == 6
|
||||
```
|
||||
```js
|
||||
function f(x, y, z) {
|
||||
return x + y + z;
|
||||
}
|
||||
// Pass each elem of array as argument
|
||||
f(...[1,2,3]) == 6
|
||||
```
|
||||
|
||||
### Let + Const
|
||||
|
||||
Block-scoped binding constructs. `let` is the new `var`. `const` is
|
||||
single-assignment. Static restrictions prevent use before assignment.
|
||||
|
||||
|
||||
```js
|
||||
function f() {
|
||||
{
|
||||
let x;
|
||||
{
|
||||
// okay, block scoped name
|
||||
const x = "sneaky";
|
||||
// error, const
|
||||
x = "foo";
|
||||
}
|
||||
// error, already declared in block
|
||||
let x = "inner";
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Iterators + For..Of
|
||||
|
||||
Iterator objects enable custom iteration like CLR IEnumerable or Java
|
||||
Iteratable. Generalize `for..in` to custom iterator-based iteration with
|
||||
`for..of`. Don’t require realizing an array, enabling lazy design patterns like
|
||||
LINQ.
|
||||
|
||||
```js
|
||||
let fibonacci = {
|
||||
[Symbol.iterator]() {
|
||||
let pre = 0, cur = 1;
|
||||
return {
|
||||
next() {
|
||||
[pre, cur] = [cur, pre + cur];
|
||||
return { done: false, value: cur }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var n of fibonacci) {
|
||||
// truncate the sequence at 1000
|
||||
if (n > 1000)
|
||||
break;
|
||||
print(n);
|
||||
}
|
||||
```
|
||||
|
||||
Iteration is based on these duck-typed interfaces (using
|
||||
[TypeScript](http://typescriptlang.org) type syntax for exposition only):
|
||||
|
||||
```ts
|
||||
interface IteratorResult {
|
||||
done: boolean;
|
||||
value: any;
|
||||
}
|
||||
interface Iterator {
|
||||
next(): IteratorResult;
|
||||
}
|
||||
interface Iterable {
|
||||
[Symbol.iterator](): Iterator
|
||||
}
|
||||
```
|
||||
|
||||
### Generators
|
||||
|
||||
Generators simplify iterator-authoring using `function*` and `yield`. A function
|
||||
declared as function* returns a Generator instance. Generators are subtypes of
|
||||
iterators which include additional `next` and `throw`. These enable values to
|
||||
flow back into the generator, so `yield` is an expression form which returns a
|
||||
value (or throws).
|
||||
|
||||
Note: Can also be used to enable ‘await’-like async programming, see also ES7
|
||||
`await` proposal.
|
||||
|
||||
```js
|
||||
var fibonacci = {
|
||||
[Symbol.iterator]: function*() {
|
||||
var pre = 0, cur = 1;
|
||||
for (;;) {
|
||||
var temp = pre;
|
||||
pre = cur;
|
||||
cur += temp;
|
||||
yield cur;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (var n of fibonacci) {
|
||||
// truncate the sequence at 1000
|
||||
if (n > 1000)
|
||||
break;
|
||||
print(n);
|
||||
}
|
||||
```
|
||||
|
||||
The generator interface is (using [TypeScript](http://typescriptlang.org) type
|
||||
syntax for exposition only):
|
||||
|
||||
```ts
|
||||
interface Generator extends Iterator {
|
||||
next(value?: any): IteratorResult;
|
||||
throw(exception: any);
|
||||
}
|
||||
```
|
||||
|
||||
### Comprehensions
|
||||
|
||||
Array and generator comprehensions provide simple declarative list processing
|
||||
similar as used in many functional programming patterns.
|
||||
|
||||
```js
|
||||
// Array comprehensions
|
||||
var results = [
|
||||
for(c of customers)
|
||||
if (c.city == "Seattle")
|
||||
{ name: c.name, age: c.age }
|
||||
]
|
||||
|
||||
// Generator comprehensions
|
||||
var results = (
|
||||
for(c of customers)
|
||||
if (c.city == "Seattle")
|
||||
{ name: c.name, age: c.age }
|
||||
)
|
||||
```
|
||||
|
||||
### Unicode
|
||||
|
||||
Non-breaking additions to support full Unicode, including new unicode literal
|
||||
form in strings and new RegExp `u` mode to handle code points, as well as new
|
||||
APIs to process strings at the 21bit code points level. These additions support
|
||||
building global apps in JavaScript.
|
||||
|
||||
```js
|
||||
// same as ES5.1
|
||||
"𠮷".length == 2
|
||||
|
||||
// new RegExp behaviour, opt-in ‘u’
|
||||
"𠮷".match(/./u)[0].length == 2
|
||||
|
||||
// new form
|
||||
"\u{20BB7}"=="𠮷" == "\uD842\uDFB7"
|
||||
|
||||
// new String ops
|
||||
"𠮷".codePointAt(0) == 0x20BB7
|
||||
|
||||
// for-of iterates code points
|
||||
for(var c of "𠮷") {
|
||||
console.log(c);
|
||||
}
|
||||
```
|
||||
|
||||
### Modules
|
||||
|
||||
Language-level support for modules for component definition. Codifies patterns
|
||||
from popular JavaScript module loaders (AMD, CommonJS). Runtime behaviour
|
||||
defined by a host-defined default loader. Implicitly async model – no code
|
||||
executes until requested modules are available and processed.
|
||||
|
||||
```js
|
||||
// lib/math.js
|
||||
export function sum(x, y) {
|
||||
return x + y;
|
||||
}
|
||||
export var pi = 3.141593;
|
||||
```
|
||||
```js
|
||||
// app.js
|
||||
module math from "lib/math";
|
||||
alert("2π = " + math.sum(math.pi, math.pi));
|
||||
```
|
||||
```js
|
||||
// otherApp.js
|
||||
import {sum, pi} from "lib/math";
|
||||
alert("2π = " + sum(pi, pi));
|
||||
```
|
||||
|
||||
Some additional features include `export default` and `export *`:
|
||||
|
||||
```js
|
||||
// lib/mathplusplus.js
|
||||
export * from "lib/math";
|
||||
export var e = 2.71828182846;
|
||||
export default function(x) {
|
||||
return Math.exp(x);
|
||||
}
|
||||
```
|
||||
```js
|
||||
// app.js
|
||||
module math from "lib/mathplusplus";
|
||||
import exp from "lib/mathplusplus";
|
||||
alert("2π = " + exp(math.pi, math.e));
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<h4>Module Formatters</h4>
|
||||
<p>
|
||||
6to5 can transpile ES6 Modules to several different formats including
|
||||
Common.js, AMD, System, and UMD. You can even create your own. For more
|
||||
details see the <a href="modules.html">modules docs</a>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
### Module Loaders
|
||||
|
||||
Module loaders support:
|
||||
- Dynamic loading
|
||||
- State isolation
|
||||
- Global namespace isolation
|
||||
- Compilation hooks
|
||||
- Nested virtualization
|
||||
|
||||
The default module loader can be configured, and new loaders can be constructed
|
||||
to evaluated and load code in isolated or constrained contexts.
|
||||
|
||||
```js
|
||||
// Dynamic loading – ‘System’ is default loader
|
||||
System.import('lib/math').then(function(m) {
|
||||
alert("2π = " + m.sum(m.pi, m.pi));
|
||||
});
|
||||
|
||||
// Create execution sandboxes – new Loaders
|
||||
var loader = new Loader({
|
||||
global: fixup(window) // replace ‘console.log’
|
||||
});
|
||||
loader.eval("console.log('hello world!');");
|
||||
|
||||
// Directly manipulate module cache
|
||||
System.get('jquery');
|
||||
System.set('jquery', Module({$: $})); // WARNING: not yet finalized
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-warning">
|
||||
<h4>Additional polyfill needed</h4>
|
||||
<p>
|
||||
Since 6to5 defaults to using common.js modules, it does not include the
|
||||
polyfill for the module loader api. Get it
|
||||
<a href="https://github.com/ModuleLoader/es6-module-loader">here</a>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<h4>Using Module Loader</h4>
|
||||
<p>
|
||||
In order to use this, you'll need to tell 6to5 to use the
|
||||
<code>system</code> module formatter. Also be sure to check out
|
||||
<a href="https://github.com/systemjs/systemjs">System.js</a>
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
|
||||
### Map + Set + WeakMap + WeakSet
|
||||
|
||||
Efficient data structures for common algorithms. WeakMaps provides leak-free
|
||||
object-key’d side tables.
|
||||
|
||||
```js
|
||||
// Sets
|
||||
var s = new Set();
|
||||
s.add("hello").add("goodbye").add("hello");
|
||||
s.size === 2;
|
||||
s.has("hello") === true;
|
||||
|
||||
// Maps
|
||||
var m = new Map();
|
||||
m.set("hello", 42);
|
||||
m.set(s, 34);
|
||||
m.get(s) == 34;
|
||||
|
||||
// Weak Maps
|
||||
var wm = new WeakMap();
|
||||
wm.set(s, { extra: 42 });
|
||||
wm.size === undefined
|
||||
|
||||
// Weak Sets
|
||||
var ws = new WeakSet();
|
||||
ws.add({ data: 42 });
|
||||
// Because the added object has no other references, it will not be held in the set
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<h4>Support via polyfill</h4>
|
||||
<p>
|
||||
In order to support Promises you must include the 6to5 Polyfill.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
### Proxies
|
||||
|
||||
Proxies enable creation of objects with the full range of behaviors available to
|
||||
host objects. Can be used for interception, object virtualization,
|
||||
logging/profiling, etc.
|
||||
|
||||
```js
|
||||
// Proxying a normal object
|
||||
var target = {};
|
||||
var handler = {
|
||||
get: function (receiver, name) {
|
||||
return `Hello, ${name}!`;
|
||||
}
|
||||
};
|
||||
|
||||
var p = new Proxy(target, handler);
|
||||
p.world === 'Hello, world!';
|
||||
```
|
||||
|
||||
```js
|
||||
// Proxying a function object
|
||||
var target = function () { return 'I am the target'; };
|
||||
var handler = {
|
||||
apply: function (receiver, ...args) {
|
||||
return 'I am the proxy';
|
||||
}
|
||||
};
|
||||
|
||||
var p = new Proxy(target, handler);
|
||||
p() === 'I am the proxy';
|
||||
```
|
||||
|
||||
There are traps available for all of the runtime-level meta-operations:
|
||||
|
||||
```js
|
||||
var handler =
|
||||
{
|
||||
get:...,
|
||||
set:...,
|
||||
has:...,
|
||||
deleteProperty:...,
|
||||
apply:...,
|
||||
construct:...,
|
||||
getOwnPropertyDescriptor:...,
|
||||
defineProperty:...,
|
||||
getPrototypeOf:...,
|
||||
setPrototypeOf:...,
|
||||
enumerate:...,
|
||||
ownKeys:...,
|
||||
preventExtensions:...,
|
||||
isExtensible:...
|
||||
}
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-danger">
|
||||
<h4>Unsupported feature</h4>
|
||||
<p>
|
||||
Due to the limitations of ES5, Proxies cannot be transpiled or polyfilled.
|
||||
See support from various
|
||||
<a href="http://kangax.github.io/compat-table/es6/#Proxy">JavaScript
|
||||
engines</a>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
### Symbols
|
||||
|
||||
Symbols enable access control for object state. Symbols allow properties to be
|
||||
keyed by either `string` (as in ES5) or `symbol`. Symbols are a new primitive
|
||||
type. Optional `name` parameter used in debugging - but is not part of identity.
|
||||
Symbols are unique (like gensym), but not private since they are exposed via
|
||||
reflection features like `Object.getOwnPropertySymbols`.
|
||||
|
||||
```js
|
||||
(function() {
|
||||
|
||||
// module scoped symbol
|
||||
var key = Symbol("key");
|
||||
|
||||
function MyClass(privateData) {
|
||||
this[key] = privateData;
|
||||
}
|
||||
|
||||
MyClass.prototype = {
|
||||
doStuff: function() {
|
||||
... this[key] ...
|
||||
}
|
||||
};
|
||||
|
||||
})();
|
||||
|
||||
var c = new MyClass("hello")
|
||||
c["key"] === undefined
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<h4>Support via polyfill</h4>
|
||||
<p>
|
||||
In order to support Promises you must include the 6to5 Polyfill.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
### Subclassable Built-ins
|
||||
In ES6, built-ins like `Array`, `Date` and DOM `Element`s can be subclassed.
|
||||
|
||||
Object construction for a function named `Ctor` now uses two-phases (both
|
||||
virtually dispatched):
|
||||
|
||||
- Call `Ctor[@@create]` to allocate the object, installing any special behavior
|
||||
- Invoke constructor on new instance to initialize
|
||||
|
||||
The known `@@create` symbol is available via `Symbol.create`. Built-ins now
|
||||
expose their `@@create` explicitly.
|
||||
|
||||
```js
|
||||
// Pseudo-code of Array
|
||||
class Array {
|
||||
constructor(...args) { /* ... */ }
|
||||
static [Symbol.create]() {
|
||||
// Install special [[DefineOwnProperty]]
|
||||
// to magically update 'length'
|
||||
}
|
||||
}
|
||||
|
||||
// User code of Array subclass
|
||||
class MyArray extends Array {
|
||||
constructor(...args) { super(...args); }
|
||||
}
|
||||
|
||||
// Two-phase 'new':
|
||||
// 1) Call @@create to allocate object
|
||||
// 2) Invoke constructor on new instance
|
||||
var arr = new MyArray();
|
||||
arr[1] = 12;
|
||||
arr.length == 2
|
||||
```
|
||||
|
||||
### Math + Number + String + Object APIs
|
||||
|
||||
Many new library additions, including core Math libraries, Array conversion
|
||||
helpers, and Object.assign for copying.
|
||||
|
||||
```js
|
||||
Number.EPSILON
|
||||
Number.isInteger(Infinity) // false
|
||||
Number.isNaN("NaN") // false
|
||||
|
||||
Math.acosh(3) // 1.762747174039086
|
||||
Math.hypot(3, 4) // 5
|
||||
Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
|
||||
|
||||
"abcde".contains("cd") // true
|
||||
"abc".repeat(3) // "abcabcabc"
|
||||
|
||||
Array.from(document.querySelectorAll('*')) // Returns a real Array
|
||||
Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
|
||||
[0, 0, 0].fill(7, 1) // [0,7,7]
|
||||
[1,2,3].findIndex(x => x == 2) // 1
|
||||
["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
|
||||
["a", "b", "c"].keys() // iterator 0, 1, 2
|
||||
["a", "b", "c"].values() // iterator "a", "b", "c"
|
||||
|
||||
Object.assign(Point, { origin: new Point(0,0) })
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-warning">
|
||||
<h4>Limited support from polyfill</h4>
|
||||
<p>
|
||||
Most of these APIs are supported by the 6to5 Polyfill. However, certain
|
||||
features are omitted for various reasons (ie.
|
||||
<code>String.prototype.normalize</code> needs a lot of additional code to
|
||||
support). You can find more polyfills
|
||||
<a href="https://github.com/addyosmani/es6-tools#polyfills">here</a>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
### Binary and Octal Literals
|
||||
Two new numeric literal forms are added for binary (`b`) and octal (`o`).
|
||||
|
||||
```js
|
||||
0b111110111 === 503 // true
|
||||
0o767 === 503 // true
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-warning">
|
||||
<h4>Only supports literal form</h4>
|
||||
<p>
|
||||
6to5 is only able to transform <code>0o767</code> and not
|
||||
<code>Number('0o767')</code>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
|
||||
### Promises
|
||||
|
||||
Promises are a library for asynchronous programming. Promises are a first class
|
||||
representation of a value that may be made available in the future. Promises are
|
||||
used in many existing JavaScript libraries.
|
||||
|
||||
```js
|
||||
function timeout(duration = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
setTimeout(resolve, duration);
|
||||
})
|
||||
}
|
||||
|
||||
var p = timeout(1000).then(() => {
|
||||
return timeout(2000);
|
||||
}).then(() => {
|
||||
throw new Error("hmm");
|
||||
}).catch(err => {
|
||||
return Promise.all([timeout(100), timeout(200)]);
|
||||
})
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<h4>Support via polyfill</h4>
|
||||
<p>
|
||||
In order to support Promises you must include the 6to5 Polyfill.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
### Reflect API
|
||||
|
||||
Full reflection API exposing the runtime-level meta-operations on objects. This
|
||||
is effectively the inverse of the Proxy API, and allows making calls
|
||||
corresponding to the same meta-operations as the proxy traps. Especially useful
|
||||
for implementing proxies.
|
||||
|
||||
```js
|
||||
// No sample yet
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-danger">
|
||||
<h4>Limited support from polyfill</h4>
|
||||
<p>
|
||||
Core.js only currently supports <code>Reflect.ownKeys</code>, if you would
|
||||
like a much more complete Reflect API, include another polyfill such as
|
||||
<a href="https://github.com/tvcutsem/harmony-reflect">Harmony Reflect</a>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
### Tail Calls
|
||||
|
||||
Calls in tail-position are guaranteed to not grow the stack unboundedly. Makes
|
||||
recursive algorithms safe in the face of unbounded inputs.
|
||||
|
||||
```js
|
||||
function factorial(n, acc = 1) {
|
||||
'use strict';
|
||||
if (n <= 1) return acc;
|
||||
return factorial(n - 1, n * acc);
|
||||
}
|
||||
|
||||
// Stack overflow in most implementations today,
|
||||
// but safe on arbitrary inputs in eS6
|
||||
factorial(100000)
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-danger">
|
||||
<h4>Unsupported feature</h4>
|
||||
<p>
|
||||
Due to high complexity of transpiling Tail Calls, 6to5 does not currently
|
||||
have them implemented. See
|
||||
<a href="https://github.com/6to5/6to5/issues/256">#256</a>.
|
||||
</p>
|
||||
</blockquote>
|
||||
@@ -1,59 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: API
|
||||
description: How to use the Node.js API.
|
||||
permalink: /docs/usage/api/
|
||||
---
|
||||
|
||||
|
||||
```javascript
|
||||
var to5 = require('6to5');
|
||||
```
|
||||
|
||||
## to5.transform
|
||||
|
||||
Transforms the passed in `code`.
|
||||
|
||||
```
|
||||
to5.transform(code, [options])
|
||||
```
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
var result = to5.transform('code();', options);
|
||||
result.code;
|
||||
result.map;
|
||||
result.ast;
|
||||
```
|
||||
|
||||
## to5.transformFile
|
||||
|
||||
Asynchronously transforms the entire contents of a file.
|
||||
|
||||
```js
|
||||
to5.transformFile(filename, [options], callback)
|
||||
```
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
to5.transformFile('filename.js', options, function (err, result) {
|
||||
result.code;
|
||||
});
|
||||
```
|
||||
|
||||
## to5.transformFileSync
|
||||
|
||||
Synchronous version of `to5.transformFile`. Returns the transformed contents of
|
||||
the `filename`.
|
||||
|
||||
```js
|
||||
to5.transformFileSync(filename, [options])
|
||||
```
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
to5.transformFileSync('filename.js', options).code;
|
||||
```
|
||||
@@ -1,59 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: Browser
|
||||
description: How to transpile in the browser.
|
||||
permalink: /docs/usage/browser/
|
||||
redirect_from: /browser.html
|
||||
---
|
||||
|
||||
<p class="lead">
|
||||
A browser version of 6to5 is available from `browser.js` inside the 6to5
|
||||
directory in an npm release.
|
||||
</p>
|
||||
|
||||
<blockquote class="to5-callout to5-callout-warning">
|
||||
<h4>Not intended for serious use</h4>
|
||||
<p>
|
||||
Compiling in the browser has a fairly limited use case, so if you are
|
||||
working on a production site you should be precompiling your scripts
|
||||
server-side. See <a href="../setup/#build-systems">setup build systems</a>
|
||||
for more information.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
## Script tags
|
||||
|
||||
When the `browser.js` file is included all scripts with the type
|
||||
`text/ecmascript-6` and `text/6to5` are automatically compiled and ran.
|
||||
|
||||
```html
|
||||
<script src="node_modules/6to5/browser.js"></script>
|
||||
<script type="text/6to5">
|
||||
class Test {
|
||||
test() {
|
||||
return 'test';
|
||||
}
|
||||
}
|
||||
|
||||
var test = new Test;
|
||||
test.test(); // "test"
|
||||
</script>
|
||||
```
|
||||
|
||||
## API
|
||||
|
||||
Programmatically transpile and execute strings of ES6 code.
|
||||
|
||||
See [options](#options) for additional documentation.
|
||||
|
||||
### `to5.transform(code, [opts])`
|
||||
|
||||
```js
|
||||
to5.transform('class Test {}').code;
|
||||
```
|
||||
|
||||
### `to5.run(code, [opts])`
|
||||
|
||||
````js
|
||||
to5.run('class Test {}');
|
||||
````
|
||||
@@ -1,99 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: CLI
|
||||
description: How to use the CLI tools.
|
||||
permalink: /docs/usage/cli/
|
||||
redirect_from: /usage.html
|
||||
---
|
||||
|
||||
<p class="lead">
|
||||
6to5 comes with a built-in CLI which can be used to compile files from the
|
||||
command line.
|
||||
</p>
|
||||
|
||||
## Install
|
||||
|
||||
Using [npm](https://www.npmjs.com/) you can install 6to5 globally, making it
|
||||
available from the command line.
|
||||
|
||||
```sh
|
||||
$ npm install --global 6to5
|
||||
```
|
||||
|
||||
## 6to5
|
||||
|
||||
#### Compile Files
|
||||
|
||||
Compile the file `script.js` and **output to stdout**.
|
||||
|
||||
```sh
|
||||
$ 6to5 script.js
|
||||
# output...
|
||||
```
|
||||
|
||||
If you would like to **output to a file** you may use `--out-file` or `-o`.
|
||||
|
||||
```sh
|
||||
$ 6to5 script.js --out-file script-compiled.js
|
||||
```
|
||||
|
||||
### Compile with Source Maps
|
||||
|
||||
If you would then like to add a **source map file** you can use
|
||||
`--source-maps` or `-s`. [Learn more about source maps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/).
|
||||
|
||||
```sh
|
||||
$ 6to5 script.js --out-file script-compiled.js --source-maps
|
||||
```
|
||||
|
||||
If you would rather have **inline source maps**, you may use
|
||||
`--source-maps-inline` or `-t`.
|
||||
|
||||
```sh
|
||||
$ 6to5 script.js --out-file script-compiled.js --source-maps-inline
|
||||
```
|
||||
|
||||
### Compile Directories
|
||||
|
||||
Compile the entire `src` directory and output it to the `lib` directory.
|
||||
|
||||
```sh
|
||||
$ 6to5 src --out-dir lib
|
||||
```
|
||||
|
||||
Compile the entire `src` directory and output it to the one concatenated file.
|
||||
|
||||
```sh
|
||||
$ 6to5 src --out-file script-compiled.js
|
||||
```
|
||||
|
||||
### Piping Files
|
||||
|
||||
Pipe a file in via stdin and output it to `script-compiled.js`
|
||||
|
||||
```sh
|
||||
$ 6to5 --out-file script-compiled.js < script.js
|
||||
```
|
||||
|
||||
## 6to5-node
|
||||
|
||||
6to5 comes with a second CLI which works exactly the same as Node.js's CLI, only
|
||||
it will compile ES6 code before running it.
|
||||
|
||||
Launch a REPL (Read-Eval-Print-Loop).
|
||||
|
||||
```sh
|
||||
$ 6to5-node
|
||||
```
|
||||
|
||||
Evaluate code.
|
||||
|
||||
```sh
|
||||
$ 6to5-node -e "class Test { }"
|
||||
```
|
||||
|
||||
Compile and run `test.js`.
|
||||
|
||||
```sh
|
||||
$ 6to5-node test
|
||||
```
|
||||
@@ -1,28 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: Experimental
|
||||
description: How to use experimental ES7 features.
|
||||
permalink: /docs/usage/experimental/
|
||||
redirect_from: /experimental.html
|
||||
---
|
||||
|
||||
> 6to5 also has experimental support for ES7 proposals.
|
||||
|
||||
<blockquote class="to5-callout to5-callout-danger">
|
||||
<h4>Subject to change</h4>
|
||||
<p>
|
||||
These proposals are subject to change so <strong><em>use with extreme
|
||||
caution</em></strong>. 6to5 may update without warning in order to track spec
|
||||
changes. Please do not use them in production applications.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
#### Usage
|
||||
|
||||
```js
|
||||
$ 6to5 --experimental
|
||||
```
|
||||
|
||||
```js
|
||||
to5.transform('code', { experimental: true });
|
||||
```
|
||||
@@ -1,22 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: JSX
|
||||
description: How to use JSX.
|
||||
permalink: /docs/usage/jsx/
|
||||
---
|
||||
|
||||
<p class="lead">
|
||||
6to5 has built-in support for React v0.12. Tags are automatically transformed
|
||||
to their equivalent <code>React.createElement(...)</code> and
|
||||
<code>displayName</code> is automatically inferred and added to all
|
||||
<code>React.createClass</code> calls.
|
||||
</p>
|
||||
|
||||
## Blacklist
|
||||
|
||||
To disable this behaviour add react to your blacklist:
|
||||
|
||||
````js
|
||||
to5.transform("code", { blacklist: ["react"] });
|
||||
$ 6to5 --blacklist react
|
||||
```
|
||||
@@ -1,260 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: Modules
|
||||
description: How to use module formatters.
|
||||
permalink: /docs/usage/modules/
|
||||
redirect_from: /modules.html
|
||||
---
|
||||
|
||||
<p class="lead">
|
||||
6to5 has the ability to transpile ES6 modules to the module system of your
|
||||
choice. You can even easily create your own.
|
||||
</p>
|
||||
|
||||
## Usage
|
||||
|
||||
```sh
|
||||
$ 6to5 --modules common script.js
|
||||
```
|
||||
|
||||
```js
|
||||
to5.transform('import "foo";', { modules: "common" });
|
||||
```
|
||||
|
||||
## Formats
|
||||
|
||||
### Common (Default)
|
||||
|
||||
**Usage**
|
||||
|
||||
```sh
|
||||
$ 6to5 --modules common
|
||||
```
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
export default test;
|
||||
|
||||
export {test};
|
||||
export var test = 5;
|
||||
|
||||
import "foo";
|
||||
|
||||
import foo from "foo";
|
||||
import * as foo from "foo";
|
||||
|
||||
import {bar} from "foo";
|
||||
import {foo as bar} from "foo";
|
||||
```
|
||||
|
||||
```js
|
||||
"use strict";
|
||||
|
||||
var _interopRequire = function (obj) {
|
||||
return obj && (obj["default"] || obj);
|
||||
};
|
||||
|
||||
exports = module.exports = test;
|
||||
|
||||
exports.test = test;
|
||||
var test = exports.test = 5;
|
||||
|
||||
require("foo");
|
||||
|
||||
var foo = _interopRequire(require("foo"));
|
||||
|
||||
var foo = require("foo");
|
||||
|
||||
var bar = require("foo").bar;
|
||||
var bar = require("foo").foo;
|
||||
```
|
||||
|
||||
### AMD
|
||||
|
||||
**Usage**
|
||||
|
||||
```sh
|
||||
$ 6to5 --modules amd
|
||||
```
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
import foo from "foo";
|
||||
|
||||
export function bar() {
|
||||
return foo("foobar");
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
define(["exports", "foo"], function (exports, _foo) {
|
||||
"use strict";
|
||||
|
||||
var _interopRequire = function (obj) {
|
||||
return obj && (obj["default"] || obj);
|
||||
};
|
||||
|
||||
exports.bar = bar;
|
||||
var foo = _interopRequire(_foo);
|
||||
|
||||
function bar() {
|
||||
return foo("foobar");
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
You can optionally specify to include the module id (using the `--amd-module-id`
|
||||
argument):
|
||||
|
||||
```js
|
||||
define("filename", ["exports", "foo"], function (exports, _foo) {})
|
||||
```
|
||||
|
||||
### System
|
||||
|
||||
**Usage**
|
||||
|
||||
```sh
|
||||
$ 6to5 --modules system
|
||||
```
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
import foo from "foo";
|
||||
|
||||
export function bar() {
|
||||
return foo("foobar");
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
System.register("bar", ["foo"], function (_export) {
|
||||
"use strict";
|
||||
|
||||
var __moduleName = "bar";
|
||||
|
||||
var foo;
|
||||
function bar() {
|
||||
return foo("foobar");
|
||||
}
|
||||
return {
|
||||
setters: [function (m) {
|
||||
foo = m.default;
|
||||
}],
|
||||
execute: function () {
|
||||
_export("bar", bar);
|
||||
}
|
||||
};
|
||||
});
|
||||
```
|
||||
|
||||
### UMD
|
||||
|
||||
**Usage**
|
||||
|
||||
```sh
|
||||
$ 6to5 --modules umd
|
||||
```
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
import foo from "foo";
|
||||
|
||||
export function bar() {
|
||||
return foo("foobar");
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
(function (factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(["exports", "foo"], factory);
|
||||
} else if (typeof exports !== "undefined") {
|
||||
factory(exports, require("foo"));
|
||||
}
|
||||
})(function (exports, _foo) {
|
||||
"use strict";
|
||||
|
||||
var _interopRequire = function (obj) {
|
||||
return obj && (obj["default"] || obj);
|
||||
};
|
||||
|
||||
exports.bar = bar;
|
||||
var foo = _interopRequire(_foo);
|
||||
|
||||
function bar() {
|
||||
return foo("foobar");
|
||||
}
|
||||
});
|
||||
```
|
||||
|
||||
### Ignore
|
||||
|
||||
**Usage**
|
||||
|
||||
```sh
|
||||
$ 6to5 --modules ignore
|
||||
```
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
import foo from "foo";
|
||||
|
||||
export function bar() {
|
||||
return foo("foobar");
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
function bar() {
|
||||
return foo("foobar");
|
||||
}
|
||||
```
|
||||
|
||||
### Custom
|
||||
|
||||
You can alternatively specify module names instead of one of the built-in types.
|
||||
|
||||
**Usage**
|
||||
|
||||
```js
|
||||
$ 6to5 --modules custom-module-formatter
|
||||
```
|
||||
|
||||
**Example**
|
||||
|
||||
**`node_modules/custom-module-formatter/index.js`**
|
||||
|
||||
```js
|
||||
module.exports = ModuleFormatter;
|
||||
|
||||
function ModuleFormatter() {}
|
||||
|
||||
ModuleFormatter.prototype.transform = function (ast) {
|
||||
// this is ran after all transformers have had their turn at modifying the ast
|
||||
// feel free to modify this however
|
||||
};
|
||||
|
||||
ModuleFormatter.prototype.importDeclaration = function (node, nodes) {
|
||||
// node is an ImportDeclaration
|
||||
};
|
||||
|
||||
ModuleFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
|
||||
// specifier is an ImportSpecifier
|
||||
// node is an ImportDeclaration
|
||||
};
|
||||
|
||||
ModuleFormatter.prototype.exportDeclaration = function (node, nodes) {
|
||||
// node is an ExportDeclaration
|
||||
};
|
||||
|
||||
ModuleFormatter.prototype.exportSpecifier = function (specifier, node, nodes) {
|
||||
// specifier is an ExportSpecifier
|
||||
// node is an ExportDeclaration
|
||||
};
|
||||
```
|
||||
@@ -1,35 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: Options
|
||||
description: Options for 6to5 transpiling.
|
||||
permalink: /docs/usage/options/
|
||||
---
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
to5.transform(code, options);
|
||||
```
|
||||
|
||||
```sh
|
||||
$ 6to5 --name=value
|
||||
```
|
||||
|
||||
## Options
|
||||
|
||||
| Option | Default | Description |
|
||||
| ------------------ | -------------------- | ------------------------------- |
|
||||
| `filename` | `"unknown"` | Filename for use in errors etc. |
|
||||
| `fileNameRelative` | `(filename)` | Filename relative to `sourceRoot`. |
|
||||
| `blacklist` | `[]` | Array of transformers to **exclude**. Run `6to5 --help` to see a full list of transformers. |
|
||||
| `whitelist` | `[]` | Array of transformers to **only** use. Run `6to5 --help` to see a full list of transformers. |
|
||||
| `modules` | `"common"` | Which module formatter to use. Run `6to5 --help` to see a full list of module formatters. |
|
||||
| `sourceMap` | `false` | If truthy, adds a `map` property to returned output. If set to `"inline"`, a comment with a sourceMappingURL directive is added to the bottom of the returned code. |
|
||||
| `sourceMapName` | `(filenameRelative)` | Set `file` on returned source map. |
|
||||
| `sourceFileName` | `(filenameRelative)` | Set `sources[0]` on returned source map. |
|
||||
| `sourceRoot` | `(moduleRoot)` | The root from which all sources are relative. |
|
||||
| `moduleRoot` | `(sourceRoot)` | Optional prefix for the AMD module formatter that will be prepend to the filename on module definitions. |
|
||||
| `amdModuleIds` | `false` | If truthy, insert an explicit id for each defined AMD module. By default, AMD modules are anonymous. |
|
||||
| `runtime` | `false` | Optionally replace all 6to5 helper declarations with a referenece to this variable. If set to `true` then the default namespace is used `to5Runtime`. |
|
||||
| `comments` | `true` | Output comments in generated output. |
|
||||
| `experimental` | `false` | Enable support for experimental ES7 features. |
|
||||
@@ -1,173 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: Playground
|
||||
description: How to use the playground.
|
||||
permalink: /docs/usage/playground/
|
||||
redirect_from: /playground.html
|
||||
---
|
||||
|
||||
> Playground is a proving ground for language ideas.
|
||||
|
||||
<blockquote class="to5-callout to5-callout-danger">
|
||||
<h4>Unofficial</h4>
|
||||
<p>
|
||||
These features are in no way endorsed by Ecma International and are not a
|
||||
part of any ECMAScript standard, nor are they necessarily on track to become
|
||||
part of any standard. <strong><em>Use with extreme caution</em></strong>.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<h4>Proposal Authors</h4>
|
||||
<p>
|
||||
If you are actively working on an
|
||||
<a href="https://github.com/tc39/ecma262">ECMAScript proposal</a>, this is a
|
||||
good place to get your ideas implemented with so that they may be tested
|
||||
with all of the latest language and API features.
|
||||
</p>
|
||||
<p>
|
||||
Please feel free to <a href="https://github.com/6to5/6to5/issues/new">open
|
||||
an issue</a> on the 6to5 repository with your WIP spec, and we can discuss
|
||||
getting it implemented. Be sure to include as much information as possible.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
$ 6to5 --playground
|
||||
```
|
||||
|
||||
```js
|
||||
to5.transform('code', { playground: true });
|
||||
```
|
||||
|
||||
<blockquote class="to5-callout to5-callout-info">
|
||||
<h4>Enables experimental</h4>
|
||||
<p>
|
||||
Enabling playground also enables experimental support.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
## Features
|
||||
|
||||
### Memoization assignment operator
|
||||
|
||||
The memoization assignment operator allows you to lazily set an object property.
|
||||
It checks whether there's a property defined on the object and if there isn't
|
||||
then the right hand value is set.
|
||||
|
||||
This means that `obj.x` in the following `var x = { x: undefined }; obj.x ?= 2;``
|
||||
will still be `undefined` because it's already been defined on the object.
|
||||
|
||||
**Uses**
|
||||
|
||||
```js
|
||||
var obj = {};
|
||||
obj.x ?= 2;
|
||||
obj.x; // 2
|
||||
|
||||
obj = { x: 1 };
|
||||
obj.x ?= 2;
|
||||
obj.x; // 1
|
||||
|
||||
obj = { x: undefined }
|
||||
obj.x ?= 2;
|
||||
obj.x; // undefined
|
||||
```
|
||||
|
||||
**Example**
|
||||
|
||||
```js
|
||||
var obj = {};
|
||||
obj.x ?= 2;
|
||||
```
|
||||
|
||||
is equivalent to
|
||||
|
||||
```js
|
||||
var obj = {};
|
||||
if (!Object.prototype.hasOwnProperty.call(obj, 'x')) obj.x = 2;
|
||||
```
|
||||
|
||||
### Method binding
|
||||
|
||||
```javascript
|
||||
var fn = obj#method;
|
||||
var fn = obj#method("foob");
|
||||
```
|
||||
|
||||
is equivalent to
|
||||
|
||||
```javascript
|
||||
var fn = obj.method.bind(obj);
|
||||
var fn = obj.method.bind(obj, "foob");
|
||||
```
|
||||
|
||||
### Method binding function shorthand
|
||||
|
||||
```javascript
|
||||
["foo", "bar"].map(#toUpperCase); // ["FOO", "BAR"]
|
||||
[1.1234, 23.53245, 3].map(#toFixed(2)); // ["1.12", "23.53", "3.00"]
|
||||
```
|
||||
|
||||
equivalent to
|
||||
|
||||
```javascript
|
||||
["foo", "bar"].map(function (val) { return val.toUpperCase(); });
|
||||
[1.1234, 23.53245, 3].map(function (val) { return val.toFixed(2); });
|
||||
```
|
||||
|
||||
### Object getter memoization
|
||||
|
||||
```js
|
||||
var foo = {
|
||||
memo bar() {
|
||||
return complex();
|
||||
}
|
||||
};
|
||||
|
||||
class Foo {
|
||||
memo bar() {
|
||||
return complex();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
is equivalent to
|
||||
|
||||
```js
|
||||
var foo = {
|
||||
get bar() {
|
||||
return Object.defineProperty(this, "bar", {
|
||||
value: complex(),
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true
|
||||
}).bar;
|
||||
}
|
||||
};
|
||||
|
||||
class Foo {
|
||||
get bar() {
|
||||
return Object.defineProperty(this, "bar", {
|
||||
value: complex(),
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
writable: true
|
||||
}).bar;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### This shorthand
|
||||
|
||||
```js
|
||||
@foo
|
||||
```
|
||||
|
||||
is equivalent to
|
||||
|
||||
```
|
||||
this.foo
|
||||
```
|
||||
@@ -1,56 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: Polyfill
|
||||
description: How to use the Polyfill.
|
||||
permalink: /docs/usage/polyfill/
|
||||
---
|
||||
|
||||
<p class="lead">
|
||||
6to5 includes a polyfill that includes a custom
|
||||
<a href="https://github.com/facebook/regenerator/blob/master/runtime.js">regenerator runtime</a>
|
||||
and <a href="https://github.com/zloirock/core-js">core.js</a>.
|
||||
</p>
|
||||
|
||||
This will emulate a full ES6 environment. This polyfill is automatically loaded
|
||||
when using `6to5-node` and `6to5/register`.
|
||||
|
||||
## Usage in Node/Browserify
|
||||
|
||||
You need to include the polyfill require at the top the **entry point** to
|
||||
your application.
|
||||
|
||||
```js
|
||||
require('6to5/polyfill');
|
||||
```
|
||||
|
||||
Fortunately, this is automatically loaded when using:
|
||||
|
||||
```js
|
||||
require('6to5/register');
|
||||
```
|
||||
|
||||
## Usage in Browser
|
||||
|
||||
Available from the `browser-polyfill.js` file within the 6to5 directory of an
|
||||
npm release. This needs to be included **before** all your compiled 6to5 code.
|
||||
You can either prepend it to your compiled code or include it in a `<script>`
|
||||
before it.
|
||||
|
||||
**NOTE:** Do not `require` this via browserify etc, use `6to5/polyfill`.
|
||||
|
||||
<blockquote class="to5-callout to5-callout-warning">
|
||||
<h4>Polyfills are not perfect</h4>
|
||||
<p>
|
||||
Due to limitations in various ES5 environments not every polyfill will work
|
||||
in every environment.
|
||||
</p>
|
||||
</blockquote>
|
||||
|
||||
<blockquote class="to5-callout to5-callout-warning">
|
||||
<h4>Certain polyfills not included</h4>
|
||||
<p>
|
||||
Certain polyfills are too large/complex for their implemented features to
|
||||
justify including them for all builds. You may have to include additional
|
||||
polyfills for a subset of ES6 features.
|
||||
</p>
|
||||
</blockquote>
|
||||
@@ -1,55 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: Require Hook
|
||||
description: How to use the require hook.
|
||||
permalink: /docs/usage/require/
|
||||
---
|
||||
|
||||
## Install
|
||||
|
||||
```sh
|
||||
$ npm install 6to5
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
require('6to5/register');
|
||||
```
|
||||
|
||||
All subsequent files required by node with the extensions `.es6`, `.es`, and
|
||||
`.js` will be transformed by 6to5. The polyfill specified in Polyfill is also
|
||||
required.
|
||||
|
||||
**NOTE:** By default all requires to `node_modules` will be ignored. You can
|
||||
override this by passing an ignore regex via:
|
||||
|
||||
```js
|
||||
require('6to5/register')({
|
||||
// This will override `node_modules` ignoring - you can alternatively pass
|
||||
// a regex
|
||||
ignore: false
|
||||
});
|
||||
```
|
||||
|
||||
## Register Options
|
||||
|
||||
```javascript
|
||||
require('6to5/register')({
|
||||
// Optional ignore regex - if any filenames **do** match this regex then they
|
||||
// aren't compiled
|
||||
ignore: /regex/,
|
||||
|
||||
// Optional only regex - if any filenames **don't** match this regex then they
|
||||
// aren't compiled
|
||||
only: /my_es6_folder/,
|
||||
|
||||
// See options above for usage
|
||||
whitelist: [],
|
||||
blacklist: [],
|
||||
|
||||
// This will remove the currently hooked extensions of .es6 and .js so you'll
|
||||
// have to add them back if you want them to be used again.
|
||||
extensions: ['.js', '.es6']
|
||||
});
|
||||
```
|
||||
@@ -1,56 +0,0 @@
|
||||
---
|
||||
layout: docs
|
||||
title: Optional Runtime
|
||||
description: How to use the optional runtime.
|
||||
permalink: /docs/usage/runtime/
|
||||
---
|
||||
|
||||
## Details
|
||||
|
||||
6to5 has a few helper functions that'll be placed at the top of the generated
|
||||
code if needed so it's not inlined multiple times throughout that file. This may
|
||||
become an issue if you have multiple files, especially when you're sending them
|
||||
to the browser. gzip alleviates most of this concern but it's still not ideal.
|
||||
|
||||
You can tell 6to5 to not place any declarations at the top of your files and
|
||||
instead just point them to a reference contained within the runtime.
|
||||
|
||||
## Usage
|
||||
|
||||
```js
|
||||
$ 6to5 --runtime
|
||||
```
|
||||
|
||||
```js
|
||||
to5.transform('code', { runtime: true });
|
||||
```
|
||||
|
||||
### Getting the runtime
|
||||
|
||||
```sh
|
||||
$ 6to5-runtime
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```js
|
||||
require('6to5').runtime();
|
||||
```
|
||||
|
||||
or from an npm release in `runtime.js` from the 6to5 directory.
|
||||
|
||||
### Customising namespace
|
||||
|
||||
You can also customise the runtime namespace by passing an optional namespace
|
||||
argument:
|
||||
|
||||
```sh
|
||||
$ 6to5-runtime myCustomNamespace
|
||||
```
|
||||
|
||||
```js
|
||||
require("6to5").runtime('myCustomNamespace');
|
||||
```
|
||||
|
||||
See [Options - runtime](../options) for documentation on changing the reference in
|
||||
generated code.
|
||||
@@ -1,5 +1,7 @@
|
||||
var transform = module.exports = require("./transformation/transform");
|
||||
|
||||
transform.version = require("../../package").version;
|
||||
|
||||
transform.transform = transform;
|
||||
|
||||
transform.run = function (code, opts) {
|
||||
|
||||
@@ -35,7 +35,8 @@ File.helpers = [
|
||||
"async-to-generator",
|
||||
"interop-require-wildcard",
|
||||
"typeof",
|
||||
"exports-wildcard"
|
||||
"extends",
|
||||
"get"
|
||||
];
|
||||
|
||||
File.excludeHelpersFromRuntime = [
|
||||
@@ -48,6 +49,7 @@ File.normaliseOptions = function (opts) {
|
||||
|
||||
_.defaults(opts, {
|
||||
experimental: false,
|
||||
reactCompat: false,
|
||||
playground: false,
|
||||
whitespace: true,
|
||||
moduleIds: opts.amdModuleIds || false,
|
||||
|
||||
@@ -61,7 +61,7 @@ Buffer.prototype.space = function () {
|
||||
Buffer.prototype.removeLast = function (cha) {
|
||||
if (!this.isLast(cha)) return;
|
||||
|
||||
this.buf = this.buf.slice(0, -1);
|
||||
this.buf = this.buf.substr(0, this.buf.length - 1);
|
||||
this.position.unshift(cha);
|
||||
};
|
||||
|
||||
@@ -77,10 +77,9 @@ Buffer.prototype.newline = function (i, removeLast) {
|
||||
if (this.endsWith("{\n")) i--;
|
||||
if (this.endsWith(util.repeat(i, "\n"))) return;
|
||||
|
||||
var self = this;
|
||||
_.times(i, function () {
|
||||
self.newline(null, removeLast);
|
||||
});
|
||||
for (var j = 0; j < i; j++) {
|
||||
this.newline(null, removeLast);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -115,13 +114,18 @@ Buffer.prototype._push = function (str) {
|
||||
};
|
||||
|
||||
Buffer.prototype.endsWith = function (str) {
|
||||
return this.buf.slice(-str.length) === str;
|
||||
var d = this.buf.length - str.length;
|
||||
return d >= 0 && this.buf.lastIndexOf(str) === d;
|
||||
};
|
||||
|
||||
Buffer.prototype.isLast = function (cha, trimRight) {
|
||||
var buf = this.buf;
|
||||
if (trimRight) buf = util.trimRight(buf);
|
||||
var last = buf[buf.length - 1];
|
||||
|
||||
var chars = [].concat(cha);
|
||||
return _.contains(chars, _.last(buf));
|
||||
if (Array.isArray(cha)) {
|
||||
return _.contains(cha, last);
|
||||
} else {
|
||||
return cha === last;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -57,8 +57,28 @@ exports.ThisExpression = function () {
|
||||
|
||||
exports.CallExpression = function (node, print) {
|
||||
print(node.callee);
|
||||
|
||||
this.push("(");
|
||||
print.join(node.arguments, { separator: ", " });
|
||||
|
||||
var separator = ",";
|
||||
|
||||
if (node._prettyCall) {
|
||||
separator += "\n";
|
||||
this.newline();
|
||||
this.indent();
|
||||
} else {
|
||||
separator += " ";
|
||||
}
|
||||
|
||||
print.join(node.arguments, {
|
||||
separator: separator
|
||||
});
|
||||
|
||||
if (node._prettyCall) {
|
||||
this.newline();
|
||||
this.dedent();
|
||||
}
|
||||
|
||||
this.push(")");
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
var t = require("../../types");
|
||||
var util = require("../../util");
|
||||
var t = require("../../types");
|
||||
|
||||
exports.WithStatement = function (node, print) {
|
||||
this.keyword("with");
|
||||
@@ -157,7 +158,24 @@ exports.DebuggerStatement = function () {
|
||||
exports.VariableDeclaration = function (node, print, parent) {
|
||||
this.push(node.kind + " ");
|
||||
|
||||
print.join(node.declarations, { separator: ", " });
|
||||
var inits = 0;
|
||||
var noInits = 0;
|
||||
for (var i in node.declarations) {
|
||||
if (node.declarations[i].init) {
|
||||
inits++;
|
||||
} else {
|
||||
noInits++;
|
||||
}
|
||||
}
|
||||
|
||||
var sep = ",";
|
||||
if (inits > noInits) { // more inits than noinits
|
||||
sep += "\n" + util.repeat(node.kind.length + 1);
|
||||
} else {
|
||||
sep += " ";
|
||||
}
|
||||
|
||||
print.join(node.declarations, { separator: sep });
|
||||
|
||||
if (!t.isFor(parent)) {
|
||||
this.semicolon();
|
||||
|
||||
@@ -6,14 +6,19 @@ var t = require("../../types");
|
||||
var _ = require("lodash");
|
||||
|
||||
var find = function (obj, node, parent) {
|
||||
if (!obj) return;
|
||||
var result;
|
||||
|
||||
_.each(obj, function (fn, type) {
|
||||
var types = Object.keys(obj);
|
||||
for (var i = 0; i < types.length; i++) {
|
||||
var type = types[i];
|
||||
|
||||
if (t["is" + type](node)) {
|
||||
var fn = obj[type];
|
||||
result = fn(node, parent);
|
||||
if (result != null) return false;
|
||||
if (result != null) break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
@@ -99,7 +104,13 @@ _.each(Node.prototype, function (fn, key) {
|
||||
Node[key] = function (node, parent) {
|
||||
var n = new Node(node, parent);
|
||||
|
||||
var args = _.toArray(arguments).slice(2);
|
||||
// Avoid leaking arguments to prevent deoptimization
|
||||
var skipCount = 2;
|
||||
var args = new Array(arguments.length - skipCount);
|
||||
for (var i = 0; i < args.length; i++) {
|
||||
args[i] = arguments[i + 2];
|
||||
}
|
||||
|
||||
return n[key].apply(n, args);
|
||||
};
|
||||
});
|
||||
|
||||
@@ -21,6 +21,13 @@ _.each([
|
||||
});
|
||||
});
|
||||
|
||||
exports.UpdateExpression = function (node, parent) {
|
||||
if (t.isMemberExpression(parent) && parent.object === node) {
|
||||
// (foo++).test()
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
exports.ObjectExpression = function (node, parent) {
|
||||
if (t.isExpressionStatement(parent)) {
|
||||
// ({ foo: "bar" });
|
||||
|
||||
@@ -1,33 +1,27 @@
|
||||
module.exports = Position;
|
||||
|
||||
var _ = require("lodash");
|
||||
|
||||
function Position() {
|
||||
this.line = 1;
|
||||
this.column = 0;
|
||||
}
|
||||
|
||||
Position.prototype.push = function (str) {
|
||||
var self = this;
|
||||
|
||||
_.each(str, function (cha) {
|
||||
if (cha === "\n") {
|
||||
self.line++;
|
||||
self.column = 0;
|
||||
for (var i = 0; i < str.length; i++) {
|
||||
if (str[i] === "\n") {
|
||||
this.line++;
|
||||
this.column = 0;
|
||||
} else {
|
||||
self.column++;
|
||||
this.column++;
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Position.prototype.unshift = function (str) {
|
||||
var self = this;
|
||||
|
||||
_.each(str, function (cha) {
|
||||
if (cha === "\n") {
|
||||
self.line--;
|
||||
for (var i = 0; i < str.length; i++) {
|
||||
if (str[i] === "\n") {
|
||||
this.line--;
|
||||
} else {
|
||||
self.column--;
|
||||
this.column--;
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
@@ -11,15 +11,18 @@ Whitespace.prototype.getNewlinesBefore = function (node) {
|
||||
var startToken;
|
||||
var endToken;
|
||||
var tokens = this.tokens;
|
||||
var token;
|
||||
|
||||
for (var i = 0; i < tokens.length; i++) {
|
||||
token = tokens[i];
|
||||
|
||||
_.each(tokens, function (token, i) {
|
||||
// this is the token this node starts with
|
||||
if (node.start === token.start) {
|
||||
startToken = tokens[i - 1];
|
||||
endToken = token;
|
||||
return false;
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return this.getNewlinesBetween(startToken, endToken);
|
||||
};
|
||||
@@ -28,15 +31,18 @@ Whitespace.prototype.getNewlinesAfter = function (node) {
|
||||
var startToken;
|
||||
var endToken;
|
||||
var tokens = this.tokens;
|
||||
var token;
|
||||
|
||||
for (var i = 0; i < tokens.length; i++) {
|
||||
token = tokens[i];
|
||||
|
||||
_.each(tokens, function (token, i) {
|
||||
// this is the token this node ends with
|
||||
if (node.end === token.end) {
|
||||
startToken = token;
|
||||
endToken = tokens[i + 1];
|
||||
return false;
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (endToken.type.type === "eof") {
|
||||
return 1;
|
||||
|
||||
@@ -3,6 +3,8 @@ var util = require("./util");
|
||||
var fs = require("fs");
|
||||
var _ = require("lodash");
|
||||
|
||||
exports.version = require("../../package").version;
|
||||
|
||||
exports.types = require("./types");
|
||||
|
||||
exports.runtime = require("./runtime-generator");
|
||||
|
||||
@@ -20,7 +20,7 @@ module.exports = function (namespace) {
|
||||
|
||||
_.each(File.helpers, function (name) {
|
||||
if (_.contains(File.excludeHelpersFromRuntime, name)) {
|
||||
return false;
|
||||
return;
|
||||
}
|
||||
|
||||
var key = t.identifier(t.toIdentifier(name));
|
||||
|
||||
@@ -9,7 +9,11 @@ function DefaultFormatter(file) {
|
||||
this.file = file;
|
||||
|
||||
this.localExports = this.getLocalExports();
|
||||
this.localImports = this.getLocalImports();
|
||||
|
||||
this.remapAssignments();
|
||||
|
||||
//this.checkCollisions();
|
||||
}
|
||||
|
||||
DefaultFormatter.prototype.getLocalExports = function () {
|
||||
@@ -27,6 +31,53 @@ DefaultFormatter.prototype.getLocalExports = function () {
|
||||
return localExports;
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.getLocalImports = function () {
|
||||
var localImports = {};
|
||||
|
||||
traverse(this.file.ast, {
|
||||
enter: function (node) {
|
||||
if (t.isImportDeclaration(node)) {
|
||||
_.extend(localImports, t.getIds(node, true));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return localImports;
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.checkCollisions = function () {
|
||||
// todo: all check export collissions
|
||||
|
||||
var localImports = this.localImports;
|
||||
var file = this.file;
|
||||
|
||||
var isLocalReference = function (node) {
|
||||
return t.isIdentifier(node) && _.has(localImports, node.name) && localImports[node.name] !== node;
|
||||
};
|
||||
|
||||
var check = function (node) {
|
||||
if (isLocalReference(node)) {
|
||||
throw file.errorWithNode(node, "Illegal assignment of module import");
|
||||
}
|
||||
};
|
||||
|
||||
traverse(file.ast, {
|
||||
enter: function (node) {
|
||||
if (t.isAssignmentExpression(node)) {
|
||||
|
||||
var left = node.left;
|
||||
if (t.isMemberExpression(left)) {
|
||||
while (left.object) left = left.object;
|
||||
}
|
||||
|
||||
check(left);
|
||||
} else if (t.isDeclaration(node)) {
|
||||
_.each(t.getIds(node, true), check);
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype.remapExportAssignment = function (node) {
|
||||
return t.assignmentExpression(
|
||||
"=",
|
||||
@@ -110,6 +161,9 @@ DefaultFormatter.prototype.getModuleName = function () {
|
||||
|
||||
moduleName += filenameRelative;
|
||||
|
||||
// normalise path separators
|
||||
moduleName = moduleName.replace(/\\/g, "/");
|
||||
|
||||
return moduleName;
|
||||
};
|
||||
|
||||
@@ -142,10 +196,11 @@ DefaultFormatter.prototype._exportSpecifier = function (getRef, specifier, node,
|
||||
nodes.push(this._exportsWildcard(getRef(), node));
|
||||
} else {
|
||||
var ref;
|
||||
if (t.isSpecifierDefault(specifier.id) || this.noInteropRequire) {
|
||||
ref = t.memberExpression(getRef(), specifier.id);
|
||||
} else {
|
||||
if (t.isSpecifierDefault(specifier) && !this.noInteropRequire) {
|
||||
// importing a default so we need to normalise it
|
||||
ref = t.callExpression(this.file.addHelper("interop-require"), [getRef()]);
|
||||
} else {
|
||||
ref = t.memberExpression(getRef(), specifier.id);
|
||||
}
|
||||
|
||||
// export { foo } from "test";
|
||||
@@ -162,7 +217,8 @@ DefaultFormatter.prototype._exportSpecifier = function (getRef, specifier, node,
|
||||
};
|
||||
|
||||
DefaultFormatter.prototype._exportsWildcard = function (objectIdentifier) {
|
||||
return t.expressionStatement(t.callExpression(this.file.addHelper("exports-wildcard"), [
|
||||
return t.expressionStatement(t.callExpression(this.file.addHelper("defaults"), [
|
||||
t.identifier("exports"),
|
||||
t.callExpression(this.file.addHelper("interop-require-wildcard"), [objectIdentifier])
|
||||
]));
|
||||
};
|
||||
|
||||
12
lib/6to5/transformation/modules/_strict.js
Normal file
12
lib/6to5/transformation/modules/_strict.js
Normal file
@@ -0,0 +1,12 @@
|
||||
var util = require("../../util");
|
||||
|
||||
module.exports = function (Parent) {
|
||||
var Constructor = function () {
|
||||
this.noInteropExport = true;
|
||||
Parent.apply(this, arguments);
|
||||
};
|
||||
|
||||
util.inherits(Constructor, Parent);
|
||||
|
||||
return Constructor;
|
||||
};
|
||||
1
lib/6to5/transformation/modules/amd-strict.js
Normal file
1
lib/6to5/transformation/modules/amd-strict.js
Normal file
@@ -0,0 +1 @@
|
||||
module.exports = require("./_strict")(require("./amd"));
|
||||
@@ -1,13 +1,14 @@
|
||||
module.exports = AMDFormatter;
|
||||
|
||||
var DefaultFormatter = require("./_default");
|
||||
var CommonFormatter = require("./common");
|
||||
var util = require("../../util");
|
||||
var t = require("../../types");
|
||||
var _ = require("lodash");
|
||||
|
||||
function AMDFormatter() {
|
||||
DefaultFormatter.apply(this, arguments);
|
||||
this.ids = {};
|
||||
CommonFormatter.apply(this, arguments);
|
||||
this.ids = {};
|
||||
}
|
||||
|
||||
util.inherits(AMDFormatter, DefaultFormatter);
|
||||
@@ -30,12 +31,15 @@ AMDFormatter.prototype.transform = function (ast) {
|
||||
|
||||
// build an array of module names
|
||||
|
||||
var names = [t.literal("exports")].concat(this.buildDependencyLiterals());
|
||||
var names = [t.literal("exports")];
|
||||
if (this.passModuleArg) names.push(t.literal("module"));
|
||||
names = names.concat(this.buildDependencyLiterals());
|
||||
names = t.arrayExpression(names);
|
||||
|
||||
// build up define container
|
||||
|
||||
var params = _.values(this.ids);
|
||||
if (this.passModuleArg) params.unshift(t.identifier("module"));
|
||||
params.unshift(t.identifier("exports"));
|
||||
|
||||
var container = t.functionExpression(null, params, t.blockStatement(body));
|
||||
@@ -96,6 +100,14 @@ AMDFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
|
||||
]));
|
||||
};
|
||||
|
||||
AMDFormatter.prototype.exportDeclaration = function (node) {
|
||||
if (node.default && !this.noInteropExport) {
|
||||
this.passModuleArg = true;
|
||||
}
|
||||
|
||||
CommonFormatter.prototype.exportDeclaration.apply(this, arguments);
|
||||
};
|
||||
|
||||
AMDFormatter.prototype.exportSpecifier = function (specifier, node, nodes) {
|
||||
var self = this;
|
||||
return this._exportSpecifier(function () {
|
||||
|
||||
1
lib/6to5/transformation/modules/common-strict.js
Normal file
1
lib/6to5/transformation/modules/common-strict.js
Normal file
@@ -0,0 +1 @@
|
||||
module.exports = require("./_strict")(require("./common"));
|
||||
@@ -61,7 +61,7 @@ CommonJSFormatter.prototype.importDeclaration = function (node, nodes) {
|
||||
};
|
||||
|
||||
CommonJSFormatter.prototype.exportDeclaration = function (node, nodes) {
|
||||
if (node.default) {
|
||||
if (node.default && !this.noInteropRequire && !this.noInteropExport) {
|
||||
var declar = node.declaration;
|
||||
var assign;
|
||||
|
||||
@@ -83,10 +83,12 @@ CommonJSFormatter.prototype.exportDeclaration = function (node, nodes) {
|
||||
// this export isn't a function so we can't hoist it to the top so we need to set it
|
||||
// at the very end of the file with something like:
|
||||
//
|
||||
// module.exports = Object.assign(exports["default"], exports)
|
||||
// module.exports = _extends(exports["default"], exports)
|
||||
//
|
||||
|
||||
assign = util.template("common-export-default-assign", true);
|
||||
assign = util.template("common-export-default-assign", {
|
||||
EXTENDS_HELPER: this.file.addHelper("extends")
|
||||
}, true);
|
||||
assign._blockHoist = 0;
|
||||
|
||||
nodes.push(assign);
|
||||
|
||||
1
lib/6to5/transformation/modules/umd-strict.js
Normal file
1
lib/6to5/transformation/modules/umd-strict.js
Normal file
@@ -0,0 +1 @@
|
||||
module.exports = require("./_strict")(require("./umd"));
|
||||
@@ -25,22 +25,36 @@ UMDFormatter.prototype.transform = function (ast) {
|
||||
// factory
|
||||
|
||||
var ids = _.values(this.ids);
|
||||
var args = [t.identifier("exports")].concat(ids);
|
||||
var args = [t.identifier("exports")];
|
||||
if (this.passModuleArg) args.push(t.identifier("module"));
|
||||
args = args.concat(ids);
|
||||
|
||||
var factory = t.functionExpression(null, args, t.blockStatement(body));
|
||||
|
||||
// runner
|
||||
|
||||
var defineArgs = [t.arrayExpression([t.literal("exports")].concat(names))];
|
||||
var defineArgs = [t.literal("exports")];
|
||||
if (this.passModuleArg) defineArgs.push(t.literal("module"));
|
||||
defineArgs = defineArgs.concat(names);
|
||||
defineArgs = [t.arrayExpression(defineArgs)];
|
||||
|
||||
var testExports = util.template("test-exports");
|
||||
var testModule = util.template("test-module");
|
||||
var commonTests = this.passModuleArg ? t.logicalExpression("&&", testExports, testModule) : testExports;
|
||||
|
||||
var commonArgs = [t.identifier("exports")];
|
||||
if (this.passModuleArg) commonArgs.push(t.identifier("module"));
|
||||
commonArgs = commonArgs.concat(names.map(function (name) {
|
||||
return t.callExpression(t.identifier("require"), [name]);
|
||||
}));
|
||||
|
||||
var moduleName = this.getModuleName();
|
||||
if (moduleName) defineArgs.unshift(t.literal(moduleName));
|
||||
|
||||
var runner = util.template("umd-runner-body", {
|
||||
AMD_ARGUMENTS: defineArgs,
|
||||
|
||||
COMMON_ARGUMENTS: names.map(function (name) {
|
||||
return t.callExpression(t.identifier("require"), [name]);
|
||||
})
|
||||
COMMON_TEST: commonTests,
|
||||
COMMON_ARGUMENTS: commonArgs
|
||||
});
|
||||
|
||||
//
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
(function () {
|
||||
if (SUPER_NAME != null) {
|
||||
SUPER_NAME.apply(this, arguments);
|
||||
}
|
||||
});
|
||||
@@ -1,3 +1,3 @@
|
||||
if (SUPER_NAME !== null) {
|
||||
SUPER_NAME.apply(this, arguments);
|
||||
if (Object.getPrototypeOf(CLASS_NAME) !== null) {
|
||||
Object.getPrototypeOf(CLASS_NAME).apply(this, arguments);
|
||||
}
|
||||
|
||||
@@ -1 +1 @@
|
||||
module.exports = Object.assign(exports["default"], exports);
|
||||
module.exports = EXTENDS_HELPER(exports["default"], exports);
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
(function (obj) {
|
||||
for (var i in obj) {
|
||||
if (exports[i] !== undefined) {
|
||||
exports[i] = obj[i];
|
||||
}
|
||||
}
|
||||
})
|
||||
9
lib/6to5/transformation/templates/extends.js
Normal file
9
lib/6to5/transformation/templates/extends.js
Normal file
@@ -0,0 +1,9 @@
|
||||
(function (target) {
|
||||
for (var i = 1; i < arguments.length; i++) {
|
||||
var source = arguments[i];
|
||||
for (var key in source) {
|
||||
target[key] = source[key];
|
||||
}
|
||||
}
|
||||
return target;
|
||||
})
|
||||
13
lib/6to5/transformation/templates/for-of-fast.js
Normal file
13
lib/6to5/transformation/templates/for-of-fast.js
Normal file
@@ -0,0 +1,13 @@
|
||||
for (var LOOP_OBJECT = OBJECT,
|
||||
IS_ARRAY = Array.isArray(LOOP_OBJECT),
|
||||
INDEX = 0,
|
||||
LOOP_OBJECT = IS_ARRAY ? LOOP_OBJECT : LOOP_OBJECT[Symbol.iterator]();;) {
|
||||
if (IS_ARRAY) {
|
||||
if (INDEX >= LOOP_OBJECT.length) break;
|
||||
ID = LOOP_OBJECT[INDEX++];
|
||||
} else {
|
||||
INDEX = LOOP_OBJECT.next();
|
||||
if (INDEX.done) break;
|
||||
ID = INDEX.value;
|
||||
}
|
||||
}
|
||||
23
lib/6to5/transformation/templates/get.js
Normal file
23
lib/6to5/transformation/templates/get.js
Normal file
@@ -0,0 +1,23 @@
|
||||
(function get(object, property, receiver) {
|
||||
var desc = Object.getOwnPropertyDescriptor(object, property);
|
||||
|
||||
if (desc === undefined) {
|
||||
var parent = Object.getPrototypeOf(object);
|
||||
|
||||
if (parent === null) {
|
||||
return undefined;
|
||||
} else {
|
||||
return get(parent, property, receiver);
|
||||
}
|
||||
} else if ("value" in desc && desc.writable) {
|
||||
return desc.value;
|
||||
} else {
|
||||
var getter = desc.get;
|
||||
|
||||
if (getter === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return getter.call(receiver);
|
||||
}
|
||||
});
|
||||
@@ -1,5 +0,0 @@
|
||||
|
||||
(function (KEY) {
|
||||
CONTENT;
|
||||
return KEY;
|
||||
})(OBJECT);
|
||||
@@ -1 +0,0 @@
|
||||
Object.defineProperties(OBJECT, PROPS);
|
||||
1
lib/6to5/transformation/templates/test-exports.js
Normal file
1
lib/6to5/transformation/templates/test-exports.js
Normal file
@@ -0,0 +1 @@
|
||||
typeof exports !== "undefined"
|
||||
1
lib/6to5/transformation/templates/test-module.js
Normal file
1
lib/6to5/transformation/templates/test-module.js
Normal file
@@ -0,0 +1 @@
|
||||
typeof module !== "undefined"
|
||||
@@ -1,7 +1,7 @@
|
||||
(function (factory) {
|
||||
if (typeof define === "function" && define.amd) {
|
||||
define(AMD_ARGUMENTS, factory);
|
||||
} else if (typeof exports !== "undefined") {
|
||||
factory(exports, COMMON_ARGUMENTS);
|
||||
} else if (COMMON_TEST) {
|
||||
factory(COMMON_ARGUMENTS);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -31,17 +31,19 @@ transform._ensureTransformerNames = function (type, keys) {
|
||||
transform.transformers = {};
|
||||
|
||||
transform.moduleFormatters = {
|
||||
common: require("./modules/common"),
|
||||
system: require("./modules/system"),
|
||||
ignore: require("./modules/ignore"),
|
||||
amd: require("./modules/amd"),
|
||||
umd: require("./modules/umd")
|
||||
commonStrict: require("./modules/common-strict"),
|
||||
umdStrict: require("./modules/umd-strict"),
|
||||
amdStrict: require("./modules/amd-strict"),
|
||||
common: require("./modules/common"),
|
||||
system: require("./modules/system"),
|
||||
ignore: require("./modules/ignore"),
|
||||
amd: require("./modules/amd"),
|
||||
umd: require("./modules/umd")
|
||||
};
|
||||
|
||||
_.each({
|
||||
// spec
|
||||
specBlockHoistFunctions: require("./transformers/spec-block-hoist-functions"),
|
||||
specNoForInOfAssignment: require("./transformers/spec-no-for-in-of-assignment"),
|
||||
specSetters: require("./transformers/spec-setters"),
|
||||
|
||||
// playground
|
||||
methodBinding: require("./transformers/playground-method-binding"),
|
||||
@@ -57,17 +59,18 @@ _.each({
|
||||
arrayComprehension: require("./transformers/es7-array-comprehension"),
|
||||
generatorComprehension: require("./transformers/es7-generator-comprehension"),
|
||||
arrowFunctions: require("./transformers/es6-arrow-functions"),
|
||||
classesFastSuper: require("./transformers/optional-classes-fast-super"),
|
||||
classes: require("./transformers/es6-classes"),
|
||||
|
||||
computedPropertyNames: require("./transformers/es6-computed-property-names"),
|
||||
|
||||
objectSpread: require("./transformers/es7-object-spread"),
|
||||
exponentiationOperator: require("./transformers/es7-exponentiation-operator"),
|
||||
spread: require("./transformers/es6-spread"),
|
||||
templateLiterals: require("./transformers/es6-template-literals"),
|
||||
propertyMethodAssignment: require("./transformers/es6-property-method-assignment"),
|
||||
computedPropertyNames: require("./transformers/es6-computed-property-names"),
|
||||
destructuring: require("./transformers/es6-destructuring"),
|
||||
defaultParameters: require("./transformers/es6-default-parameters"),
|
||||
forOfFast: require("./transformers/optional-for-of-fast"),
|
||||
forOf: require("./transformers/es6-for-of"),
|
||||
unicodeRegex: require("./transformers/es6-unicode-regex"),
|
||||
abstractReferences: require("./transformers/es7-abstract-references"),
|
||||
|
||||
@@ -3,36 +3,11 @@ var util = require("../../util");
|
||||
var t = require("../../types");
|
||||
|
||||
exports.ClassDeclaration = function (node, parent, file, scope) {
|
||||
var closure = true;
|
||||
if (t.isProgram(parent) || t.isBlockStatement(parent)) {
|
||||
closure = false;
|
||||
}
|
||||
|
||||
var factory = new Class(node, file, scope, closure);
|
||||
var newNode = factory.run();
|
||||
if (factory.closure) {
|
||||
if (closure) {
|
||||
// declaration in an expression context...
|
||||
// export default class Foo {}
|
||||
scope.push({
|
||||
kind: "var",
|
||||
key: node.id.key,
|
||||
id: node.id
|
||||
});
|
||||
return t.assignmentExpression("=", node.id, newNode);
|
||||
} else {
|
||||
// has a super class or PrivateDeclaration etc
|
||||
return t.variableDeclaration("let", [
|
||||
t.variableDeclarator(node.id, newNode)
|
||||
]);
|
||||
}
|
||||
} else {
|
||||
return newNode;
|
||||
}
|
||||
return new Class(node, file, scope, true).run();
|
||||
};
|
||||
|
||||
exports.ClassExpression = function (node, parent, file, scope) {
|
||||
return new Class(node, file, scope, true).run();
|
||||
return new Class(node, file, scope, false).run();
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -44,11 +19,11 @@ exports.ClassExpression = function (node, parent, file, scope) {
|
||||
* @param {Boolean} closure
|
||||
*/
|
||||
|
||||
function Class(node, file, scope, closure) {
|
||||
this.closure = closure;
|
||||
this.scope = scope;
|
||||
this.node = node;
|
||||
this.file = file;
|
||||
function Class(node, file, scope, isStatement) {
|
||||
this.isStatement = isStatement;
|
||||
this.scope = scope;
|
||||
this.node = node;
|
||||
this.file = file;
|
||||
|
||||
this.hasInstanceMutators = false;
|
||||
this.hasStaticMutators = false;
|
||||
@@ -83,17 +58,20 @@ Class.prototype.run = function () {
|
||||
t.variableDeclarator(className, constructor)
|
||||
]));
|
||||
|
||||
var closureArgs = [];
|
||||
var closureParams = [];
|
||||
|
||||
//
|
||||
|
||||
if (superName) {
|
||||
this.closure = true;
|
||||
closureArgs.push(superName);
|
||||
|
||||
// so we're only evaluating it once
|
||||
var superRef = this.scope.generateUidBasedOnNode(superName, this.file);
|
||||
body.unshift(t.variableDeclaration("var", [
|
||||
t.variableDeclarator(superRef, superName)
|
||||
]));
|
||||
superName = superRef;
|
||||
if (!t.isIdentifier(superName)) {
|
||||
var superRef = this.scope.generateUidBasedOnNode(superName, this.file);
|
||||
superName = superRef;
|
||||
}
|
||||
|
||||
closureParams.push(superName);
|
||||
|
||||
this.superName = superName;
|
||||
body.push(t.expressionStatement(t.callExpression(file.addHelper("inherits"), [className, superName])));
|
||||
@@ -103,19 +81,25 @@ Class.prototype.run = function () {
|
||||
|
||||
t.inheritsComments(body[0], this.node);
|
||||
|
||||
if (this.closure) {
|
||||
if (body.length === 1) {
|
||||
// only a constructor so no need for a closure container
|
||||
return constructor;
|
||||
} else {
|
||||
body.push(t.returnStatement(className));
|
||||
return t.callExpression(
|
||||
t.functionExpression(null, [], t.blockStatement(body)),
|
||||
[]
|
||||
);
|
||||
}
|
||||
var init;
|
||||
|
||||
if (body.length === 1) {
|
||||
// only a constructor so no need for a closure container
|
||||
init = constructor;
|
||||
} else {
|
||||
return body;
|
||||
body.push(t.returnStatement(className));
|
||||
init = t.callExpression(
|
||||
t.functionExpression(null, closureParams, t.blockStatement(body)),
|
||||
closureArgs
|
||||
);
|
||||
}
|
||||
|
||||
if (this.isStatement) {
|
||||
return t.variableDeclaration("let", [
|
||||
t.variableDeclarator(className, init)
|
||||
]);
|
||||
} else {
|
||||
return init;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -149,7 +133,7 @@ Class.prototype.buildBody = function () {
|
||||
|
||||
if (!this.hasConstructor && superName && !t.isFalsyExpression(superName)) {
|
||||
constructor.body.body.push(util.template("class-super-constructor-call", {
|
||||
SUPER_NAME: superName
|
||||
CLASS_NAME: className
|
||||
}, true));
|
||||
}
|
||||
|
||||
@@ -157,15 +141,11 @@ Class.prototype.buildBody = function () {
|
||||
var staticProps;
|
||||
|
||||
if (this.hasInstanceMutators) {
|
||||
var protoId = util.template("prototype-identifier", {
|
||||
CLASS_NAME: className
|
||||
});
|
||||
|
||||
instanceProps = util.buildDefineProperties(this.instanceMutatorMap, protoId);
|
||||
instanceProps = util.buildDefineProperties(this.instanceMutatorMap);
|
||||
}
|
||||
|
||||
if (this.hasStaticMutators) {
|
||||
staticProps = util.buildDefineProperties(this.staticMutatorMap, className);
|
||||
staticProps = util.buildDefineProperties(this.staticMutatorMap);
|
||||
}
|
||||
|
||||
if (instanceProps || staticProps) {
|
||||
@@ -190,70 +170,49 @@ Class.prototype.pushMethod = function (node) {
|
||||
var methodName = node.key;
|
||||
|
||||
var kind = node.kind;
|
||||
var mutatorMap = this.instanceMutatorMap;
|
||||
if (node.static) {
|
||||
this.hasStaticMutators = true;
|
||||
mutatorMap = this.staticMutatorMap;
|
||||
} else {
|
||||
this.hasInstanceMutators = true;
|
||||
}
|
||||
|
||||
if (kind === "") {
|
||||
// method
|
||||
|
||||
var className = this.className;
|
||||
if (!node.static) className = t.memberExpression(className, t.identifier("prototype"));
|
||||
methodName = t.memberExpression(className, methodName, node.computed);
|
||||
|
||||
var expr = t.expressionStatement(t.assignmentExpression("=", methodName, node.value));
|
||||
t.inheritsComments(expr, node);
|
||||
this.body.push(expr);
|
||||
} else {
|
||||
// mutator
|
||||
var mutatorMap = this.instanceMutatorMap;
|
||||
if (node.static) {
|
||||
this.hasStaticMutators = true;
|
||||
mutatorMap = this.staticMutatorMap;
|
||||
} else {
|
||||
this.hasInstanceMutators = true;
|
||||
}
|
||||
util.pushMutatorMap(mutatorMap, methodName, kind, node);
|
||||
kind = "value";
|
||||
}
|
||||
|
||||
util.pushMutatorMap(mutatorMap, methodName, kind, node.computed, node);
|
||||
};
|
||||
|
||||
/**
|
||||
* Given a `methodNode`, produce a `MemberExpression` super class reference.
|
||||
* Gets a node representing the super class value of the named property.
|
||||
*
|
||||
* @param {Node} methodNode MethodDefinition
|
||||
* @param {Node} node Identifier
|
||||
* @param {Node} parent
|
||||
* @example
|
||||
*
|
||||
* _get(Object.getPrototypeOf(CLASS.prototype), "METHOD", this)
|
||||
*
|
||||
* @param {Node} property
|
||||
* @param {boolean} isStatic
|
||||
* @param {boolean} isComputed
|
||||
*
|
||||
* @returns {Node}
|
||||
*/
|
||||
|
||||
Class.prototype.superIdentifier = function (methodNode, id, parent) {
|
||||
var methodName = methodNode.key;
|
||||
var superName = this.superName || t.identifier("Function");
|
||||
|
||||
if (parent.property === id) {
|
||||
return;
|
||||
} else if (t.isCallExpression(parent, { callee: id })) {
|
||||
// super(); -> ClassName.prototype.MethodName.call(this);
|
||||
parent.arguments.unshift(t.thisExpression());
|
||||
|
||||
if (methodName.name === "constructor") {
|
||||
// constructor() { super(); }
|
||||
return t.memberExpression(superName, t.identifier("call"));
|
||||
} else {
|
||||
id = superName;
|
||||
|
||||
// foo() { super(); }
|
||||
if (!methodNode.static) {
|
||||
id = t.memberExpression(id, t.identifier("prototype"));
|
||||
}
|
||||
|
||||
id = t.memberExpression(id, methodName, methodNode.computed);
|
||||
return t.memberExpression(id, t.identifier("call"));
|
||||
}
|
||||
} else if (t.isMemberExpression(parent) && !methodNode.static) {
|
||||
// super.test -> ClassName.prototype.test
|
||||
return t.memberExpression(superName, t.identifier("prototype"));
|
||||
} else {
|
||||
return superName;
|
||||
}
|
||||
Class.prototype.superProperty = function (property, isStatic, isComputed, thisExpression) {
|
||||
return t.callExpression(
|
||||
this.file.addHelper("get"),
|
||||
[
|
||||
t.callExpression(
|
||||
t.memberExpression(t.identifier("Object"), t.identifier("getPrototypeOf")),
|
||||
[
|
||||
isStatic ? this.className : t.memberExpression(this.className, t.identifier("prototype"))
|
||||
]
|
||||
),
|
||||
isComputed ? property : t.literal(property.name),
|
||||
thisExpression
|
||||
]
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -264,20 +223,53 @@ Class.prototype.superIdentifier = function (methodNode, id, parent) {
|
||||
|
||||
Class.prototype.replaceInstanceSuperReferences = function (methodNode) {
|
||||
var method = methodNode.value;
|
||||
var self = this;
|
||||
var self = this;
|
||||
|
||||
traverse(method, {
|
||||
enter: function (node, parent) {
|
||||
var property;
|
||||
var computed;
|
||||
var args;
|
||||
|
||||
if (t.isIdentifier(node, { name: "super" })) {
|
||||
return self.superIdentifier(methodNode, node, parent);
|
||||
if (!(t.isMemberExpression(parent) && !parent.computed && parent.property === node)) {
|
||||
throw self.file.errorWithNode(node, "illegal use of bare super");
|
||||
}
|
||||
} else if (t.isCallExpression(node)) {
|
||||
var callee = node.callee;
|
||||
if (!t.isMemberExpression(callee)) return;
|
||||
if (callee.object.name !== "super") return;
|
||||
if (t.isIdentifier(callee, { name: "super" })) {
|
||||
// super(); -> _get(Object.getPrototypeOf(ClassName), "MethodName", this).call(this);
|
||||
property = methodNode.key;
|
||||
computed = methodNode.computed;
|
||||
args = node.arguments;
|
||||
} else {
|
||||
if (!t.isMemberExpression(callee)) return;
|
||||
if (callee.object.name !== "super") return;
|
||||
|
||||
// super.test(); -> ClassName.prototype.MethodName.call(this);
|
||||
t.appendToMemberExpression(callee, t.identifier("call"));
|
||||
node.arguments.unshift(t.thisExpression());
|
||||
// super.test(); -> _get(Object.getPrototypeOf(ClassName.prototype), "test", this).call(this);
|
||||
property = callee.property;
|
||||
computed = callee.computed;
|
||||
args = node.arguments;
|
||||
}
|
||||
} else if (t.isMemberExpression(node)) {
|
||||
if (!t.isIdentifier(node.object, { name: "super" })) return;
|
||||
|
||||
// super.name; -> _get(Object.getPrototypeOf(ClassName.prototype), "name", this);
|
||||
property = node.property;
|
||||
computed = node.computed;
|
||||
}
|
||||
|
||||
if (property) {
|
||||
var thisExpression = t.thisExpression();
|
||||
var superProperty = self.superProperty(property, methodNode.static, computed, thisExpression);
|
||||
if (args) {
|
||||
return t.callExpression(
|
||||
t.memberExpression(superProperty, t.identifier("call"), false),
|
||||
[thisExpression].concat(args)
|
||||
);
|
||||
} else {
|
||||
return superProperty;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -290,7 +282,7 @@ Class.prototype.replaceInstanceSuperReferences = function (methodNode) {
|
||||
*/
|
||||
|
||||
Class.prototype.pushConstructor = function (method) {
|
||||
if (method.kind !== "") {
|
||||
if (method.kind) {
|
||||
throw this.file.errorWithNode(method, "illegal kind for constructor method");
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ exports.ObjectExpression = function (node, parent, file, scope) {
|
||||
var i;
|
||||
|
||||
for (i in node.properties) {
|
||||
hasComputed = t.isProperty(node.properties[i], { computed: true });
|
||||
hasComputed = t.isProperty(node.properties[i], { computed: true, kind: "init" });
|
||||
if (hasComputed) break;
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ exports.ObjectExpression = function (node, parent, file, scope) {
|
||||
|
||||
for (i in props) {
|
||||
prop = props[i];
|
||||
if (prop.kind !== "init") continue;
|
||||
|
||||
key = prop.key;
|
||||
|
||||
if (!prop.computed && t.isIdentifier(key)) {
|
||||
@@ -44,7 +46,7 @@ exports.ObjectExpression = function (node, parent, file, scope) {
|
||||
broken = true;
|
||||
}
|
||||
|
||||
if (!broken || t.isLiteral(t.toComputedKey(prop, prop.key), { value: "__proto__" })) {
|
||||
if (prop.kind !== "init" || !broken || t.isLiteral(t.toComputedKey(prop, prop.key), { value: "__proto__" })) {
|
||||
initProps.push(prop);
|
||||
props[i] = null;
|
||||
}
|
||||
|
||||
@@ -134,7 +134,7 @@ var pushPattern = function (opts) {
|
||||
var file = opts.file;
|
||||
var scope = opts.scope;
|
||||
|
||||
if (!t.isMemberExpression(parentId) && !t.isIdentifier(parentId)) {
|
||||
if (!t.isArrayExpression(parentId) && !t.isMemberExpression(parentId) && !t.isIdentifier(parentId)) {
|
||||
var key = scope.generateUidBasedOnNode(parentId, file);
|
||||
|
||||
nodes.push(t.variableDeclaration("var", [
|
||||
@@ -300,10 +300,17 @@ exports.VariableDeclaration = function (node, parent, file, scope) {
|
||||
file: file,
|
||||
scope: scope
|
||||
};
|
||||
|
||||
if (t.isPattern(pattern) && patternId) {
|
||||
pushPattern(opts);
|
||||
|
||||
if (+i !== node.declarations.length - 1) {
|
||||
// we aren't the last declarator so let's just make the
|
||||
// last transformed node inherit from us
|
||||
t.inherits(nodes[nodes.length - 1], declar);
|
||||
}
|
||||
} else {
|
||||
nodes.push(buildVariableAssign(opts, declar.id, declar.init));
|
||||
nodes.push(t.inherits(buildVariableAssign(opts, declar.id, declar.init), declar));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ exports.ForOfStatement = function (node, parent, file, scope) {
|
||||
var stepKey = file.generateUidIdentifier("step", scope);
|
||||
var stepValue = t.memberExpression(stepKey, t.identifier("value"));
|
||||
|
||||
if (t.isIdentifier(left)) {
|
||||
if (t.isIdentifier(left) || t.isPattern(left)) {
|
||||
declar = t.expressionStatement(t.assignmentExpression("=", left, stepValue));
|
||||
} else if (t.isVariableDeclaration(left)) {
|
||||
declar = t.variableDeclaration(left.kind, [
|
||||
|
||||
@@ -37,7 +37,6 @@ exports.VariableDeclaration = function (node, parent) {
|
||||
exports.Loop = function (node, parent, file, scope) {
|
||||
var init = node.left || node.init;
|
||||
if (isLet(init, node)) {
|
||||
t.ensureBlock(node);
|
||||
node.body._letDeclars = [init];
|
||||
}
|
||||
|
||||
|
||||
@@ -46,14 +46,14 @@ exports.Property = function (node, parent, file, scope) {
|
||||
}
|
||||
};
|
||||
|
||||
exports.ObjectExpression = function (node, parent, file, scope) {
|
||||
exports.ObjectExpression = function (node) {
|
||||
var mutatorMap = {};
|
||||
var hasAny = false;
|
||||
|
||||
node.properties = node.properties.filter(function (prop) {
|
||||
if (prop.kind === "get" || prop.kind === "set") {
|
||||
hasAny = true;
|
||||
util.pushMutatorMap(mutatorMap, prop.key, prop.kind, prop.value);
|
||||
util.pushMutatorMap(mutatorMap, prop.key, prop.kind, prop.computed, prop.value);
|
||||
return false;
|
||||
} else {
|
||||
return true;
|
||||
@@ -62,21 +62,8 @@ exports.ObjectExpression = function (node, parent, file, scope) {
|
||||
|
||||
if (!hasAny) return;
|
||||
|
||||
if (node.properties.length) {
|
||||
var objId = scope.generateUidBasedOnNode(parent, file);
|
||||
|
||||
return util.template("object-define-properties-closure", {
|
||||
KEY: objId,
|
||||
OBJECT: node,
|
||||
CONTENT: util.template("object-define-properties", {
|
||||
OBJECT: objId,
|
||||
PROPS: util.buildDefineProperties(mutatorMap)
|
||||
})
|
||||
});
|
||||
} else {
|
||||
return util.template("object-define-properties", {
|
||||
OBJECT: node,
|
||||
PROPS: util.buildDefineProperties(mutatorMap)
|
||||
});
|
||||
}
|
||||
return t.callExpression(
|
||||
t.memberExpression(t.identifier("Object"), t.identifier("defineProperties")),
|
||||
[node, util.buildDefineProperties(mutatorMap)]
|
||||
);
|
||||
};
|
||||
|
||||
@@ -4,7 +4,7 @@ var t = require("../../types");
|
||||
|
||||
exports.experimental = true;
|
||||
|
||||
exports.ObjectExpression = function (node) {
|
||||
exports.ObjectExpression = function (node, parent, file) {
|
||||
var hasSpread = false;
|
||||
var i;
|
||||
var prop;
|
||||
@@ -42,5 +42,5 @@ exports.ObjectExpression = function (node) {
|
||||
args.unshift(t.objectExpression([]));
|
||||
}
|
||||
|
||||
return t.callExpression(t.memberExpression(t.identifier("Object"), t.identifier("assign")), args);
|
||||
return t.callExpression(file.addHelper("extends"), args);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
var traverse = require("../../traverse");
|
||||
var util = require("../../util");
|
||||
var t = require("../../types");
|
||||
|
||||
exports.optional = true;
|
||||
|
||||
exports.Class = function (node) {
|
||||
var superClass = node.superClass || t.identifier("Function");
|
||||
|
||||
var hasConstructor = false;
|
||||
var body = node.body.body;
|
||||
|
||||
for (var i in body) {
|
||||
var methodNode = body[i];
|
||||
|
||||
hasConstructor = hasConstructor || methodNode.key.name === "constructor";
|
||||
|
||||
traverse(methodNode, {
|
||||
enter: function (node, parent) {
|
||||
if (t.isIdentifier(node, { name: "super" })) {
|
||||
return superIdentifier(superClass, methodNode, node, parent);
|
||||
} else if (t.isCallExpression(node)) {
|
||||
var callee = node.callee;
|
||||
if (!t.isMemberExpression(callee)) return;
|
||||
if (callee.object.name !== "super") return;
|
||||
|
||||
// super.test(); -> ClassName.prototype.MethodName.call(this);
|
||||
t.appendToMemberExpression(callee, t.identifier("call"));
|
||||
node.arguments.unshift(t.thisExpression());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (node.superClass && !hasConstructor) {
|
||||
body.unshift(t.methodDefinition(
|
||||
t.identifier("constructor"),
|
||||
util.template("class-super-constructor-call-fast", {
|
||||
SUPER_NAME: superClass
|
||||
})
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
var superIdentifier = function (superClass, methodNode, id, parent) {
|
||||
var methodName = methodNode.key;
|
||||
|
||||
if (parent.property === id) {
|
||||
return;
|
||||
} else if (t.isCallExpression(parent, { callee: id })) {
|
||||
// super(); -> ClassName.prototype.MethodName.call(this);
|
||||
parent.arguments.unshift(t.thisExpression());
|
||||
|
||||
if (methodName.name === "constructor") {
|
||||
// constructor() { super(); }
|
||||
return t.memberExpression(superClass, t.identifier("call"));
|
||||
} else {
|
||||
id = superClass;
|
||||
|
||||
// foo() { super(); }
|
||||
if (!methodNode.static) {
|
||||
id = t.memberExpression(id, t.identifier("prototype"));
|
||||
}
|
||||
|
||||
id = t.memberExpression(id, methodName, methodNode.computed);
|
||||
return t.memberExpression(id, t.identifier("call"));
|
||||
}
|
||||
} else if (t.isMemberExpression(parent) && !methodNode.static) {
|
||||
// super.test -> ClassName.prototype.test
|
||||
return t.memberExpression(superClass, t.identifier("prototype"));
|
||||
} else {
|
||||
return superClass;
|
||||
}
|
||||
};
|
||||
@@ -31,8 +31,8 @@ exports.ast = {
|
||||
this.skip();
|
||||
return t.prependToMemberExpression(node, file._coreId);
|
||||
}
|
||||
} else if (t.isIdentifier(node) && !t.isMemberExpression(parent) && t.isReferenced(node, parent) && coreHas(node)) {
|
||||
// new Promise -> new _core.Promise
|
||||
} else if (t.isIdentifier(node) && !t.isMemberExpression(parent) && t.isReferenced(node, parent) && node.name === "Symbol") {
|
||||
// new Symbol -> new _core.Symbol
|
||||
return t.memberExpression(file._coreId, node);
|
||||
} else if (t.isCallExpression(node)) {
|
||||
// arr[Symbol.iterator]() -> _core.$for.getIterator(arr)
|
||||
|
||||
37
lib/6to5/transformation/transformers/optional-for-of-fast.js
Normal file
37
lib/6to5/transformation/transformers/optional-for-of-fast.js
Normal file
@@ -0,0 +1,37 @@
|
||||
var util = require("../../util");
|
||||
var t = require("../../types");
|
||||
|
||||
exports.optional = true;
|
||||
|
||||
exports.ForOfStatement = function (node, parent, file, scope) {
|
||||
var left = node.left;
|
||||
var declar, id;
|
||||
|
||||
if (t.isIdentifier(left) || t.isPattern(left)) {
|
||||
id = left;
|
||||
} else if (t.isVariableDeclaration(left)) {
|
||||
id = left.declarations[0].id;
|
||||
declar = t.variableDeclaration(left.kind, [
|
||||
t.variableDeclarator(id)
|
||||
]);
|
||||
} else {
|
||||
throw file.errorWithNode(left, "Unknown node type " + left.type + " in ForOfStatement");
|
||||
}
|
||||
|
||||
var node2 = util.template("for-of-fast", {
|
||||
LOOP_OBJECT: file.generateUidIdentifier("loopObject", scope),
|
||||
IS_ARRAY: file.generateUidIdentifier("isArray", scope),
|
||||
OBJECT: node.right,
|
||||
INDEX: file.generateUidIdentifier("i", scope),
|
||||
ID: id
|
||||
});
|
||||
|
||||
t.inheritsComments(node2, node);
|
||||
t.ensureBlock(node);
|
||||
|
||||
var block = node2.body;
|
||||
if (declar) block.body.unshift(declar);
|
||||
block.body = block.body.concat(node.body.body);
|
||||
|
||||
return node2;
|
||||
};
|
||||
@@ -1,8 +1,6 @@
|
||||
var t = require("../../types");
|
||||
var _ = require("lodash");
|
||||
|
||||
var OBJECT_ASSIGN_MEMBER = t.memberExpression(t.identifier("Object"), t.identifier("assign"));
|
||||
|
||||
var isProtoKey = function (node) {
|
||||
return t.isLiteral(t.toComputedKey(node, node.key), { value: "__proto__" });
|
||||
};
|
||||
@@ -43,7 +41,7 @@ exports.ExpressionStatement = function (node, parent, file) {
|
||||
}
|
||||
};
|
||||
|
||||
exports.ObjectExpression = function (node) {
|
||||
exports.ObjectExpression = function (node, parent, file) {
|
||||
var proto;
|
||||
|
||||
for (var i in node.properties) {
|
||||
@@ -58,6 +56,6 @@ exports.ObjectExpression = function (node) {
|
||||
if (proto) {
|
||||
var args = [t.objectExpression([]), proto];
|
||||
if (node.properties.length) args.push(node);
|
||||
return t.callExpression(OBJECT_ASSIGN_MEMBER, args);
|
||||
return t.callExpression(file.addHelper("extends"), args);
|
||||
}
|
||||
};
|
||||
|
||||
45
lib/6to5/transformation/transformers/react.js
vendored
45
lib/6to5/transformation/transformers/react.js
vendored
@@ -32,12 +32,17 @@ exports.XJSExpressionContainer = function (node) {
|
||||
exports.XJSAttribute = {
|
||||
exit: function (node) {
|
||||
var value = node.value || t.literal(true);
|
||||
return t.property("init", node.name, value);
|
||||
return t.inherits(t.property("init", node.name, value), node);
|
||||
}
|
||||
};
|
||||
|
||||
var isTag = function(tagName) {
|
||||
return (/^[a-z]|\-/).test(tagName);
|
||||
};
|
||||
|
||||
exports.XJSOpeningElement = {
|
||||
exit: function (node) {
|
||||
exit: function (node, parent, file) {
|
||||
var reactCompat = file.opts.reactCompat;
|
||||
var tagExpr = node.name;
|
||||
var args = [];
|
||||
|
||||
@@ -48,10 +53,12 @@ exports.XJSOpeningElement = {
|
||||
tagName = tagExpr.value;
|
||||
}
|
||||
|
||||
if (tagName && (/[a-z]/.exec(tagName[0]) || tagName.indexOf("-") >= 0)) {
|
||||
args.push(t.literal(tagName));
|
||||
} else {
|
||||
args.push(tagExpr);
|
||||
if (!reactCompat) {
|
||||
if (tagName && isTag(tagName)) {
|
||||
args.push(t.literal(tagName));
|
||||
} else {
|
||||
args.push(tagExpr);
|
||||
}
|
||||
}
|
||||
|
||||
var props = node.attributes;
|
||||
@@ -96,7 +103,21 @@ exports.XJSOpeningElement = {
|
||||
|
||||
args.push(props);
|
||||
|
||||
tagExpr = t.memberExpression(t.identifier("React"), t.identifier("createElement"));
|
||||
if (reactCompat) {
|
||||
if (tagName && isTag(tagName)) {
|
||||
return t.callExpression(
|
||||
t.memberExpression(
|
||||
t.memberExpression(t.identifier("React"), t.identifier("DOM")),
|
||||
tagExpr,
|
||||
t.isLiteral(tagExpr)
|
||||
),
|
||||
args
|
||||
);
|
||||
}
|
||||
} else {
|
||||
tagExpr = t.memberExpression(t.identifier("React"), t.identifier("createElement"));
|
||||
}
|
||||
|
||||
return t.callExpression(tagExpr, args);
|
||||
}
|
||||
};
|
||||
@@ -119,16 +140,16 @@ exports.XJSElement = {
|
||||
var isLastLine = +i === lines.length - 1;
|
||||
|
||||
// replace rendered whitespace tabs with spaces
|
||||
var trimmedLine = line.replace(/\t/g, ' ');
|
||||
var trimmedLine = line.replace(/\t/g, " ");
|
||||
|
||||
// trim whitespace touching a newline
|
||||
if (!isFirstLine) {
|
||||
trimmedLine = trimmedLine.replace(/^[ ]+/, '');
|
||||
trimmedLine = trimmedLine.replace(/^[ ]+/, "");
|
||||
}
|
||||
|
||||
// trim whitespace touching an endline
|
||||
if (!isLastLine) {
|
||||
trimmedLine = trimmedLine.replace(/[ ]+$/, '');
|
||||
trimmedLine = trimmedLine.replace(/[ ]+$/, "");
|
||||
}
|
||||
|
||||
if (trimmedLine) {
|
||||
@@ -144,6 +165,10 @@ exports.XJSElement = {
|
||||
callExpr.arguments.push(child);
|
||||
}
|
||||
|
||||
if (callExpr.arguments.length >= 3) {
|
||||
callExpr._prettyCall = true;
|
||||
}
|
||||
|
||||
return t.inherits(callExpr, node);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,18 +0,0 @@
|
||||
var t = require("../../types");
|
||||
|
||||
exports.BlockStatement = function (node, parent) {
|
||||
if (t.isFunction(parent)) return;
|
||||
|
||||
node.body = node.body.map(function (node) {
|
||||
if (t.isFunction(node)) {
|
||||
node.type = "FunctionExpression";
|
||||
var declar = t.variableDeclaration("let", [
|
||||
t.variableDeclarator(node.id, node)
|
||||
]);
|
||||
declar._blockHoist = true;
|
||||
return declar;
|
||||
} else {
|
||||
return node;
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,5 +1,4 @@
|
||||
var esutils = require("esutils");
|
||||
var t = require("../../types");
|
||||
var t = require("../../types");
|
||||
|
||||
exports.MemberExpression = function (node) {
|
||||
var prop = node.property;
|
||||
@@ -7,7 +6,7 @@ exports.MemberExpression = function (node) {
|
||||
// computed literal that is a valid identifier
|
||||
node.property = t.identifier(prop.value);
|
||||
node.computed = false;
|
||||
} else if (!node.computed && t.isIdentifier(prop) && esutils.keyword.isKeywordES6(prop.name, true)) {
|
||||
} else if (!node.computed && t.isIdentifier(prop) && !t.isValidIdentifier(prop.name)) {
|
||||
node.property = t.literal(prop.name);
|
||||
node.computed = true;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
var esutils = require("esutils");
|
||||
var t = require("../../types");
|
||||
var t = require("../../types");
|
||||
|
||||
exports.Property = function (node) {
|
||||
var key = node.key;
|
||||
@@ -7,7 +6,7 @@ exports.Property = function (node) {
|
||||
// property key is a literal but a valid identifier
|
||||
node.key = t.identifier(key.value);
|
||||
node.computed = false;
|
||||
} else if (!node.computed && t.isIdentifier(key) && esutils.keyword.isKeywordES6(key.name, true)) {
|
||||
} else if (!node.computed && t.isIdentifier(key) && !t.isValidIdentifier(key.name)) {
|
||||
// property key is a keyword
|
||||
node.key = t.literal(key.name);
|
||||
}
|
||||
|
||||
6
lib/6to5/transformation/transformers/spec-setters.js
Normal file
6
lib/6to5/transformation/transformers/spec-setters.js
Normal file
@@ -0,0 +1,6 @@
|
||||
exports.MethodDefinition =
|
||||
exports.Property = function (node, parent, file) {
|
||||
if (node.kind === "set" && node.value.params.length !== 1) {
|
||||
throw file.errorWithNode(node.value, "Setters must have only one parameter");
|
||||
}
|
||||
};
|
||||
@@ -4,15 +4,101 @@ var Scope = require("./scope");
|
||||
var t = require("../types");
|
||||
var _ = require("lodash");
|
||||
|
||||
function TraversalContext(previousContext) {
|
||||
this.didSkip = false;
|
||||
this.didRemove = false;
|
||||
this.didStop = false;
|
||||
this.didFlatten = previousContext ? previousContext.didFlatten : false;
|
||||
}
|
||||
|
||||
TraversalContext.prototype.flatten = function () {
|
||||
this.didFlatten = true;
|
||||
};
|
||||
|
||||
TraversalContext.prototype.remove = function () {
|
||||
this.didRemove = true;
|
||||
this.skip();
|
||||
};
|
||||
|
||||
TraversalContext.prototype.skip = function () {
|
||||
this.didSkip = true;
|
||||
};
|
||||
|
||||
TraversalContext.prototype.stop = function () {
|
||||
this.didStop = true;
|
||||
this.skip();
|
||||
};
|
||||
|
||||
TraversalContext.prototype.maybeReplace = function (result, obj, key, node) {
|
||||
if (result === false) return node;
|
||||
if (result == null) return node;
|
||||
|
||||
var isArray = Array.isArray(result);
|
||||
|
||||
// inherit comments from original node to the first replacement node
|
||||
var inheritTo = result;
|
||||
if (isArray) inheritTo = result[0];
|
||||
if (inheritTo) t.inheritsComments(inheritTo, node);
|
||||
|
||||
// replace the node
|
||||
node = obj[key] = result;
|
||||
|
||||
// we're replacing a statement or block node with an array of statements so we better
|
||||
// ensure that it's a block
|
||||
if (isArray && _.contains(t.STATEMENT_OR_BLOCK_KEYS, key) && !t.isBlockStatement(obj)) {
|
||||
t.ensureBlock(obj, key);
|
||||
}
|
||||
|
||||
if (isArray) {
|
||||
this.flatten();
|
||||
}
|
||||
|
||||
return node;
|
||||
};
|
||||
|
||||
TraversalContext.prototype.visit = function (obj, key, opts, scope, parent) {
|
||||
var node = obj[key];
|
||||
if (!node) return;
|
||||
|
||||
// type is blacklisted
|
||||
if (opts.blacklist && opts.blacklist.indexOf(node.type) > -1) return;
|
||||
|
||||
var result;
|
||||
var ourScope = scope;
|
||||
if (t.isScope(node)) ourScope = new Scope(node, scope);
|
||||
|
||||
// enter
|
||||
if (opts.enter) {
|
||||
result = opts.enter.call(this, node, parent, ourScope);
|
||||
node = this.maybeReplace(result, obj, key, node);
|
||||
|
||||
if (this.didRemove) {
|
||||
obj[key] = null;
|
||||
this.flatten();
|
||||
}
|
||||
|
||||
// stop traversal
|
||||
if (this.didSkip) return;
|
||||
}
|
||||
|
||||
// traverse node
|
||||
traverse(node, opts, ourScope);
|
||||
|
||||
// exit
|
||||
if (opts.exit) {
|
||||
result = opts.exit.call(this, node, parent, ourScope);
|
||||
node = this.maybeReplace(result, obj, key, node);
|
||||
}
|
||||
};
|
||||
|
||||
function traverse(parent, opts, scope) {
|
||||
// falsy node
|
||||
if (!parent) return;
|
||||
|
||||
// array of nodes
|
||||
if (_.isArray(parent)) {
|
||||
_.each(parent, function (node) {
|
||||
traverse(node, opts, scope);
|
||||
});
|
||||
if (Array.isArray(parent)) {
|
||||
for (var i = 0; i < parent.length; i++)
|
||||
traverse(parent[i], opts, scope);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -21,99 +107,21 @@ function traverse(parent, opts, scope) {
|
||||
if (!keys) return;
|
||||
|
||||
opts = opts || {};
|
||||
var context = null;
|
||||
|
||||
var stopped = false;
|
||||
|
||||
for (var i in keys) {
|
||||
var key = keys[i];
|
||||
for (var j = 0; j < keys.length; j++) {
|
||||
var key = keys[j];
|
||||
var nodes = parent[key];
|
||||
if (!nodes) continue;
|
||||
|
||||
var flatten = false;
|
||||
|
||||
var handle = function (obj, key) {
|
||||
var node = obj[key];
|
||||
if (!node) return;
|
||||
|
||||
// type is blacklisted
|
||||
if (opts.blacklist && opts.blacklist.indexOf(node.type) > -1) return;
|
||||
|
||||
// replace node
|
||||
var maybeReplace = function (result) {
|
||||
if (result === false) return;
|
||||
if (result == null) return;
|
||||
|
||||
var isArray = _.isArray(result);
|
||||
|
||||
// inherit comments from original node to the first replacement node
|
||||
var inheritTo = result;
|
||||
if (isArray) inheritTo = result[0];
|
||||
if (inheritTo) t.inheritsComments(inheritTo, node);
|
||||
|
||||
// replace the node
|
||||
node = obj[key] = result;
|
||||
|
||||
if (isArray) flatten = true;
|
||||
|
||||
// we're replacing a statement or block node with an array of statements so we better
|
||||
// ensure that it's a block
|
||||
if (isArray && _.contains(t.STATEMENT_OR_BLOCK_KEYS, key) && !t.isBlockStatement(obj)) {
|
||||
t.ensureBlock(obj, key);
|
||||
}
|
||||
};
|
||||
|
||||
var skipped = false;
|
||||
var removed = false;
|
||||
|
||||
var context = {
|
||||
stop: function () {
|
||||
skipped = stopped = true;
|
||||
},
|
||||
|
||||
skip: function () {
|
||||
skipped = true;
|
||||
},
|
||||
|
||||
remove: function () {
|
||||
this.skip();
|
||||
removed = true;
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
var ourScope = scope;
|
||||
if (t.isScope(node)) ourScope = new Scope(node, scope);
|
||||
|
||||
// enter
|
||||
if (opts.enter) {
|
||||
var result = opts.enter.call(context, node, parent, ourScope);
|
||||
maybeReplace(result);
|
||||
|
||||
if (removed) {
|
||||
obj[key] = null;
|
||||
flatten = true;
|
||||
}
|
||||
|
||||
// stop iteration
|
||||
if (skipped) return;
|
||||
if (Array.isArray(nodes)) {
|
||||
for (var k = 0; k < nodes.length; k++) {
|
||||
context = new TraversalContext(context);
|
||||
context.visit(nodes, k, opts, scope, parent);
|
||||
if (context.didStop) return;
|
||||
}
|
||||
|
||||
// traverse node
|
||||
traverse(node, opts, ourScope);
|
||||
|
||||
// exit
|
||||
if (opts.exit) {
|
||||
maybeReplace(opts.exit.call(context, node, parent, ourScope));
|
||||
}
|
||||
};
|
||||
|
||||
if (_.isArray(nodes)) {
|
||||
for (i in nodes) {
|
||||
handle(nodes, i);
|
||||
if (stopped) return;
|
||||
}
|
||||
|
||||
if (flatten) {
|
||||
if (context && context.didFlatten) {
|
||||
parent[key] = _.flatten(parent[key]);
|
||||
|
||||
if (key === "body") {
|
||||
@@ -122,8 +130,9 @@ function traverse(parent, opts, scope) {
|
||||
}
|
||||
}
|
||||
} else {
|
||||
handle(parent, key);
|
||||
if (stopped) return;
|
||||
context = new TraversalContext(context);
|
||||
context.visit(parent, key, opts, scope, parent);
|
||||
if (context.didStop) return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,13 @@ function Scope(block, parent) {
|
||||
}
|
||||
|
||||
var vars = require("jshint/src/vars");
|
||||
Scope.defaultDeclarations = _.flatten([vars.newEcmaIdentifiers, vars.node, vars.ecmaIdentifiers, vars.reservedVars].map(_.keys));
|
||||
|
||||
Scope.defaultDeclarations = _.flatten([
|
||||
vars.newEcmaIdentifiers,
|
||||
vars.node,
|
||||
vars.ecmaIdentifiers,
|
||||
vars.reservedVars
|
||||
].map(_.keys));
|
||||
|
||||
Scope.add = function (node, references) {
|
||||
if (!node) return;
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
"Literal": ["value"],
|
||||
"LogicalExpression": ["operator", "left", "right"],
|
||||
"MemberExpression": ["object", "property", "computed"],
|
||||
"MethodDefinition": ["key", "value", "computed", "kind"],
|
||||
"NewExpression": ["callee", "arguments"],
|
||||
"ObjectExpression": ["properties"],
|
||||
"Program": ["body"],
|
||||
|
||||
@@ -320,7 +320,11 @@ t.toBlock = function (node, parent) {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (!_.isArray(node)) {
|
||||
if (t.isEmptyStatement(node)) {
|
||||
node = [];
|
||||
}
|
||||
|
||||
if (!Array.isArray(node)) {
|
||||
if (!t.isStatement(node)) {
|
||||
if (t.isFunction(parent)) {
|
||||
node = t.returnStatement(node);
|
||||
@@ -355,16 +359,24 @@ t.getIds = function (node, map, ignoreTypes) {
|
||||
if (!id) continue;
|
||||
if (_.contains(ignoreTypes, id.type)) continue;
|
||||
|
||||
var nodeKey = t.getIds.nodes[id.type];
|
||||
var nodeKeys = t.getIds.nodes[id.type];
|
||||
var arrKeys = t.getIds.arrays[id.type];
|
||||
|
||||
var i, key;
|
||||
|
||||
if (t.isIdentifier(id)) {
|
||||
ids[id.name] = id;
|
||||
} else if (nodeKey) {
|
||||
if (id[nodeKey]) search.push(id[nodeKey]);
|
||||
} else if (nodeKeys) {
|
||||
for (i in nodeKeys) {
|
||||
key = nodeKeys[i];
|
||||
if (id[key]) {
|
||||
search.push(id[key]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (arrKeys) {
|
||||
for (var i in arrKeys) {
|
||||
var key = arrKeys[i];
|
||||
for (i in arrKeys) {
|
||||
key = arrKeys[i];
|
||||
search = search.concat(id[key] || []);
|
||||
}
|
||||
}
|
||||
@@ -375,15 +387,16 @@ t.getIds = function (node, map, ignoreTypes) {
|
||||
};
|
||||
|
||||
t.getIds.nodes = {
|
||||
AssignmentExpression: "left",
|
||||
ImportSpecifier: "name",
|
||||
ExportSpecifier: "name",
|
||||
VariableDeclarator: "id",
|
||||
FunctionDeclaration: "id",
|
||||
ClassDeclaration: "id",
|
||||
MemeberExpression: "object",
|
||||
SpreadElement: "argument",
|
||||
Property: "value"
|
||||
AssignmentExpression: ["left"],
|
||||
ImportBatchSpecifier: ["name"],
|
||||
ImportSpecifier: ["name", "id"],
|
||||
ExportSpecifier: ["name", "id"],
|
||||
VariableDeclarator: ["id"],
|
||||
FunctionDeclaration: ["id"],
|
||||
ClassDeclaration: ["id"],
|
||||
MemeberExpression: ["object"],
|
||||
SpreadElement: ["argument"],
|
||||
Property: ["value"]
|
||||
};
|
||||
|
||||
t.getIds.arrays = {
|
||||
|
||||
@@ -39,7 +39,7 @@ exports.list = function (val) {
|
||||
|
||||
exports.regexify = function (val) {
|
||||
if (!val) return new RegExp(/.^/);
|
||||
if (_.isArray(val)) val = val.join("|");
|
||||
if (Array.isArray(val)) val = val.join("|");
|
||||
if (_.isString(val)) return new RegExp(val);
|
||||
if (_.isRegExp(val)) return val;
|
||||
throw new TypeError("illegal type for regexify");
|
||||
@@ -48,7 +48,7 @@ exports.regexify = function (val) {
|
||||
exports.arrayify = function (val) {
|
||||
if (!val) return [];
|
||||
if (_.isString(val)) return exports.list(val);
|
||||
if (_.isArray(val)) return val;
|
||||
if (Array.isArray(val)) return val;
|
||||
throw new TypeError("illegal type for arrayify");
|
||||
};
|
||||
|
||||
@@ -65,12 +65,12 @@ exports.sourceMapToComment = function (map) {
|
||||
return "//# sourceMappingURL=data:application/json;base64," + base64;
|
||||
};
|
||||
|
||||
exports.pushMutatorMap = function (mutatorMap, key, kind, method) {
|
||||
exports.pushMutatorMap = function (mutatorMap, key, kind, computed, method) {
|
||||
var alias;
|
||||
|
||||
if (t.isIdentifier(key)) {
|
||||
alias = key.name;
|
||||
if (method.computed) alias = "computed:" + alias;
|
||||
if (computed) alias = "computed:" + alias;
|
||||
} else if (t.isLiteral(key)) {
|
||||
alias = String(key.value);
|
||||
} else {
|
||||
@@ -86,7 +86,7 @@ exports.pushMutatorMap = function (mutatorMap, key, kind, method) {
|
||||
mutatorMap[alias] = map;
|
||||
|
||||
map._key = key;
|
||||
if (method.computed) {
|
||||
if (computed) {
|
||||
map._computed = true;
|
||||
}
|
||||
|
||||
@@ -101,7 +101,12 @@ exports.buildDefineProperties = function (mutatorMap) {
|
||||
|
||||
var propNode = t.property("init", map._key, mapNode, map._computed);
|
||||
|
||||
if (!map.get && !map.set) {
|
||||
map.writable = t.literal(true);
|
||||
}
|
||||
|
||||
map.enumerable = t.literal(true);
|
||||
map.configurable = t.literal(true);
|
||||
|
||||
_.each(map, function (node, key) {
|
||||
if (key[0] === "_") return;
|
||||
@@ -146,10 +151,10 @@ exports.template = function (name, nodes, keepExpression) {
|
||||
var node = template.body[0];
|
||||
|
||||
if (!keepExpression && t.isExpressionStatement(node)) {
|
||||
node = node.expression;
|
||||
return node.expression;
|
||||
} else {
|
||||
return node;
|
||||
}
|
||||
|
||||
return node;
|
||||
};
|
||||
|
||||
exports.codeFrame = function (lines, lineNumber, colNumber) {
|
||||
@@ -188,7 +193,13 @@ exports.codeFrame = function (lines, lineNumber, colNumber) {
|
||||
|
||||
exports.repeat = function (width, cha) {
|
||||
cha = cha || " ";
|
||||
return new Array(width + 1).join(cha);
|
||||
|
||||
var result = "";
|
||||
for (var i = 0; i < width; i++) {
|
||||
result += cha;
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
exports.normaliseAst = function (ast, comments, tokens) {
|
||||
@@ -256,7 +267,7 @@ var loadTemplates = function () {
|
||||
if (!fs.existsSync(templatesLoc)) {
|
||||
throw new Error("no templates directory - this is most likely the " +
|
||||
"result of a broken `npm publish`. Please report to " +
|
||||
"https://githut.com/6to5/6to5/issues");
|
||||
"https://github.com/6to5/6to5/issues");
|
||||
}
|
||||
|
||||
_.each(fs.readdirSync(templatesLoc), function (name) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "6to5",
|
||||
"description": "Turn ES6 code into readable vanilla ES5 with source maps",
|
||||
"version": "2.6.2",
|
||||
"version": "2.10.0",
|
||||
"author": "Sebastian McKenzie <sebmck@gmail.com>",
|
||||
"homepage": "https://github.com/6to5/6to5",
|
||||
"repository": {
|
||||
@@ -39,11 +39,11 @@
|
||||
"test": "make test"
|
||||
},
|
||||
"dependencies": {
|
||||
"acorn-6to5": "0.11.1-11",
|
||||
"acorn-6to5": "0.11.1-13",
|
||||
"ast-types": "~0.6.1",
|
||||
"chokidar": "0.11.1",
|
||||
"commander": "2.5.0",
|
||||
"core-js": "^0.4.0",
|
||||
"core-js": "^0.4.1",
|
||||
"estraverse": "1.8.0",
|
||||
"esutils": "1.1.6",
|
||||
"esvalid": "^1.1.0",
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
if (!process.env.ALL_6TO5_TESTS) return;
|
||||
|
||||
require("./_transformation-helper")({
|
||||
name: "esnext"
|
||||
});
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
class Animal {
|
||||
class Base {
|
||||
get sound() {
|
||||
return 'I am a ' + this.type + '.';
|
||||
}
|
||||
}
|
||||
|
||||
class Animal extends Base {}
|
||||
|
||||
class Cat extends Animal {
|
||||
get type() { return 'cat'; }
|
||||
|
||||
|
||||
@@ -7,4 +7,5 @@ var test = {
|
||||
* Inside bracket init
|
||||
*/
|
||||
"b"]: "2"
|
||||
}, ok = 42;
|
||||
},
|
||||
ok = 42;
|
||||
|
||||
@@ -3,6 +3,7 @@ function test() {
|
||||
// Leading to VariableDeclarator
|
||||
// Leading to VariableDeclarator
|
||||
i = 20,
|
||||
|
||||
// Leading to VariableDeclarator
|
||||
// Leading to VariableDeclarator
|
||||
j = 20;
|
||||
|
||||
@@ -5,6 +5,7 @@ function test() {
|
||||
* Leading to VariableDeclarator
|
||||
*/
|
||||
i = 20,
|
||||
|
||||
/*
|
||||
* Leading to VariableDeclarator
|
||||
* Leading to VariableDeclarator
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
function* foo() {
|
||||
var a = yield wat(), b = 2;
|
||||
var a = yield wat(),
|
||||
b = 2;
|
||||
var c = yield a = b;
|
||||
yield a, yield b;
|
||||
yield a = b;
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
++i;
|
||||
i++;
|
||||
(foo++).test();
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
++i;
|
||||
i++;
|
||||
(foo++).test();
|
||||
|
||||
@@ -8,6 +8,9 @@ const foo = "foo";
|
||||
let foo, bar = "bar";
|
||||
var foo, bar = "bar";
|
||||
|
||||
let foo = "foo", bar = "bar";
|
||||
var foo = "foo", bar = "bar";
|
||||
const foo = "foo", bar = "bar";
|
||||
let foo = "foo",
|
||||
bar = "bar";
|
||||
var foo = "foo",
|
||||
bar = "bar";
|
||||
const foo = "foo",
|
||||
bar = "bar";
|
||||
|
||||
@@ -3,7 +3,6 @@ class Test extends Foo {
|
||||
woops.super.test();
|
||||
super();
|
||||
super.test();
|
||||
foob(super);
|
||||
|
||||
super(...arguments);
|
||||
super("test", ...arguments);
|
||||
|
||||
@@ -1,6 +1,33 @@
|
||||
"use strict";
|
||||
|
||||
var _slice = Array.prototype.slice;
|
||||
var _prototypeProperties = function (child, staticProps, instanceProps) {
|
||||
if (staticProps) Object.defineProperties(child, staticProps);
|
||||
if (instanceProps) Object.defineProperties(child.prototype, instanceProps);
|
||||
};
|
||||
|
||||
var _get = function get(object, property, receiver) {
|
||||
var desc = Object.getOwnPropertyDescriptor(object, property);
|
||||
|
||||
if (desc === undefined) {
|
||||
var parent = Object.getPrototypeOf(object);
|
||||
|
||||
if (parent === null) {
|
||||
return undefined;
|
||||
} else {
|
||||
return get(parent, property, receiver);
|
||||
}
|
||||
} else if ("value" in desc && desc.writable) {
|
||||
return desc.value;
|
||||
} else {
|
||||
var getter = desc.get;
|
||||
if (getter === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return getter.call(receiver);
|
||||
}
|
||||
};
|
||||
|
||||
var _inherits = function (child, parent) {
|
||||
if (typeof parent !== "function" && parent !== null) {
|
||||
throw new TypeError("Super expression must either be null or a function, not " + typeof parent);
|
||||
@@ -16,37 +43,47 @@ var _inherits = function (child, parent) {
|
||||
if (parent) child.__proto__ = parent;
|
||||
};
|
||||
|
||||
var Test = (function () {
|
||||
var _Foo = Foo;
|
||||
var Test = (function (Foo) {
|
||||
var Test = function Test() {
|
||||
var _Foo$prototype$test, _Foo$prototype$test2;
|
||||
var _get2, _get3, _get4, _get5;
|
||||
woops["super"].test();
|
||||
_Foo.call(this);
|
||||
_Foo.prototype.test.call(this);
|
||||
foob(_Foo);
|
||||
_get(Object.getPrototypeOf(Test.prototype), "constructor", this).call(this);
|
||||
_get(Object.getPrototypeOf(Test.prototype), "test", this).call(this);
|
||||
|
||||
_Foo.call.apply(_Foo, [this].concat(_slice.call(arguments)));
|
||||
_Foo.call.apply(_Foo, [this, "test"].concat(_slice.call(arguments)));
|
||||
(_get2 = _get(Object.getPrototypeOf(Test.prototype), "constructor", this)).call.apply(_get2, [this].concat(_slice.call(arguments)));
|
||||
(_get3 = _get(Object.getPrototypeOf(Test.prototype), "constructor", this)).call.apply(_get3, [this, "test"].concat(_slice.call(arguments)));
|
||||
|
||||
(_Foo$prototype$test = _Foo.prototype.test).call.apply(_Foo$prototype$test, [this].concat(_slice.call(arguments)));
|
||||
(_Foo$prototype$test2 = _Foo.prototype.test).call.apply(_Foo$prototype$test2, [this, "test"].concat(_slice.call(arguments)));
|
||||
(_get4 = _get(Object.getPrototypeOf(Test.prototype), "test", this)).call.apply(_get4, [this].concat(_slice.call(arguments)));
|
||||
(_get5 = _get(Object.getPrototypeOf(Test.prototype), "test", this)).call.apply(_get5, [this, "test"].concat(_slice.call(arguments)));
|
||||
};
|
||||
|
||||
_inherits(Test, _Foo);
|
||||
_inherits(Test, Foo);
|
||||
|
||||
Test.prototype.test = function () {
|
||||
var _Foo$prototype$test3, _Foo$prototype$test4;
|
||||
_Foo.prototype.test.call(this);
|
||||
(_Foo$prototype$test3 = _Foo.prototype.test).call.apply(_Foo$prototype$test3, [this].concat(_slice.call(arguments)));
|
||||
(_Foo$prototype$test4 = _Foo.prototype.test).call.apply(_Foo$prototype$test4, [this, "test"].concat(_slice.call(arguments)));
|
||||
};
|
||||
|
||||
Test.foo = function () {
|
||||
var _Foo$foo, _Foo$foo2;
|
||||
_Foo.foo.call(this);
|
||||
(_Foo$foo = _Foo.foo).call.apply(_Foo$foo, [this].concat(_slice.call(arguments)));
|
||||
(_Foo$foo2 = _Foo.foo).call.apply(_Foo$foo2, [this, "test"].concat(_slice.call(arguments)));
|
||||
};
|
||||
_prototypeProperties(Test, {
|
||||
foo: {
|
||||
value: function () {
|
||||
var _get6, _get7;
|
||||
_get(Object.getPrototypeOf(Test), "foo", this).call(this);
|
||||
(_get6 = _get(Object.getPrototypeOf(Test), "foo", this)).call.apply(_get6, [this].concat(_slice.call(arguments)));
|
||||
(_get7 = _get(Object.getPrototypeOf(Test), "foo", this)).call.apply(_get7, [this, "test"].concat(_slice.call(arguments)));
|
||||
},
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
}
|
||||
}, {
|
||||
test: {
|
||||
value: function () {
|
||||
var _get8, _get9;
|
||||
_get(Object.getPrototypeOf(Test.prototype), "test", this).call(this);
|
||||
(_get8 = _get(Object.getPrototypeOf(Test.prototype), "test", this)).call.apply(_get8, [this].concat(_slice.call(arguments)));
|
||||
(_get9 = _get(Object.getPrototypeOf(Test.prototype), "test", this)).call.apply(_get9, [this, "test"].concat(_slice.call(arguments)));
|
||||
},
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
}
|
||||
});
|
||||
|
||||
return Test;
|
||||
})();
|
||||
})(Foo);
|
||||
|
||||
@@ -1,5 +1,27 @@
|
||||
"use strict";
|
||||
|
||||
var _get = function get(object, property, receiver) {
|
||||
var desc = Object.getOwnPropertyDescriptor(object, property);
|
||||
|
||||
if (desc === undefined) {
|
||||
var parent = Object.getPrototypeOf(object);
|
||||
|
||||
if (parent === null) {
|
||||
return undefined;
|
||||
} else {
|
||||
return get(parent, property, receiver);
|
||||
}
|
||||
} else if ("value" in desc && desc.writable) {
|
||||
return desc.value;
|
||||
} else {
|
||||
var getter = desc.get;
|
||||
if (getter === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return getter.call(receiver);
|
||||
}
|
||||
};
|
||||
|
||||
var _inherits = function (child, parent) {
|
||||
if (typeof parent !== "function" && parent !== null) {
|
||||
throw new TypeError("Super expression must either be null or a function, not " + typeof parent);
|
||||
@@ -15,14 +37,13 @@ var _inherits = function (child, parent) {
|
||||
if (parent) child.__proto__ = parent;
|
||||
};
|
||||
|
||||
var Test = (function () {
|
||||
var _Foo = Foo;
|
||||
var Test = (function (Foo) {
|
||||
var Test = function Test() {
|
||||
_Foo.prototype.test;
|
||||
_Foo.prototype.test.whatever;
|
||||
_get(Object.getPrototypeOf(Test.prototype), "test", this);
|
||||
_get(Object.getPrototypeOf(Test.prototype), "test", this).whatever;
|
||||
};
|
||||
|
||||
_inherits(Test, _Foo);
|
||||
_inherits(Test, Foo);
|
||||
|
||||
return Test;
|
||||
})();
|
||||
})(Foo);
|
||||
|
||||
5
test/fixtures/transformation/es6-classes/bare-super/actual.js
vendored
Normal file
5
test/fixtures/transformation/es6-classes/bare-super/actual.js
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
class Test {
|
||||
constructor() {
|
||||
console.log(super);
|
||||
}
|
||||
}
|
||||
3
test/fixtures/transformation/es6-classes/bare-super/options.json
vendored
Normal file
3
test/fixtures/transformation/es6-classes/bare-super/options.json
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"throws": "illegal use of bare super"
|
||||
}
|
||||
@@ -1,5 +1,32 @@
|
||||
"use strict";
|
||||
|
||||
var _prototypeProperties = function (child, staticProps, instanceProps) {
|
||||
if (staticProps) Object.defineProperties(child, staticProps);
|
||||
if (instanceProps) Object.defineProperties(child.prototype, instanceProps);
|
||||
};
|
||||
|
||||
var _get = function get(object, property, receiver) {
|
||||
var desc = Object.getOwnPropertyDescriptor(object, property);
|
||||
|
||||
if (desc === undefined) {
|
||||
var parent = Object.getPrototypeOf(object);
|
||||
|
||||
if (parent === null) {
|
||||
return undefined;
|
||||
} else {
|
||||
return get(parent, property, receiver);
|
||||
}
|
||||
} else if ("value" in desc && desc.writable) {
|
||||
return desc.value;
|
||||
} else {
|
||||
var getter = desc.get;
|
||||
if (getter === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
return getter.call(receiver);
|
||||
}
|
||||
};
|
||||
|
||||
var _inherits = function (child, parent) {
|
||||
if (typeof parent !== "function" && parent !== null) {
|
||||
throw new TypeError("Super expression must either be null or a function, not " + typeof parent);
|
||||
@@ -15,18 +42,24 @@ var _inherits = function (child, parent) {
|
||||
if (parent) child.__proto__ = parent;
|
||||
};
|
||||
|
||||
var Test = (function () {
|
||||
var _Foo = Foo;
|
||||
var Test = (function (Foo) {
|
||||
var Test = function Test() {
|
||||
_Foo.prototype.test.whatever();
|
||||
_Foo.prototype.test.call(this);
|
||||
_get(Object.getPrototypeOf(Test.prototype), "test", this).whatever();
|
||||
_get(Object.getPrototypeOf(Test.prototype), "test", this).call(this);
|
||||
};
|
||||
|
||||
_inherits(Test, _Foo);
|
||||
_inherits(Test, Foo);
|
||||
|
||||
Test.test = function () {
|
||||
return _Foo.wow.call(this);
|
||||
};
|
||||
_prototypeProperties(Test, {
|
||||
test: {
|
||||
value: function () {
|
||||
return _get(Object.getPrototypeOf(Test), "wow", this).call(this);
|
||||
},
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
}
|
||||
});
|
||||
|
||||
return Test;
|
||||
})();
|
||||
})(Foo);
|
||||
|
||||
@@ -19,13 +19,12 @@ var Test = function Test() {
|
||||
this.state = "test";
|
||||
};
|
||||
|
||||
var Foo = (function () {
|
||||
var _Bar = Bar;
|
||||
var Foo = (function (Bar) {
|
||||
var Foo = function Foo() {
|
||||
this.state = "test";
|
||||
};
|
||||
|
||||
_inherits(Foo, _Bar);
|
||||
_inherits(Foo, Bar);
|
||||
|
||||
return Foo;
|
||||
})();
|
||||
})(Bar);
|
||||
|
||||
@@ -5,16 +5,21 @@ var _prototypeProperties = function (child, staticProps, instanceProps) {
|
||||
if (instanceProps) Object.defineProperties(child.prototype, instanceProps);
|
||||
};
|
||||
|
||||
var Test = function Test() {};
|
||||
var Test = (function () {
|
||||
var Test = function Test() {};
|
||||
|
||||
_prototypeProperties(Test, null, {
|
||||
test: {
|
||||
get: function () {
|
||||
return 5 + 5;
|
||||
},
|
||||
set: function (val) {
|
||||
this._test = val;
|
||||
},
|
||||
enumerable: true
|
||||
}
|
||||
});
|
||||
_prototypeProperties(Test, null, {
|
||||
test: {
|
||||
get: function () {
|
||||
return 5 + 5;
|
||||
},
|
||||
set: function (val) {
|
||||
this._test = val;
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
}
|
||||
});
|
||||
|
||||
return Test;
|
||||
})();
|
||||
|
||||
@@ -5,13 +5,18 @@ var _prototypeProperties = function (child, staticProps, instanceProps) {
|
||||
if (instanceProps) Object.defineProperties(child.prototype, instanceProps);
|
||||
};
|
||||
|
||||
var Test = function Test() {};
|
||||
var Test = (function () {
|
||||
var Test = function Test() {};
|
||||
|
||||
_prototypeProperties(Test, null, {
|
||||
test: {
|
||||
get: function () {
|
||||
return 5 + 5;
|
||||
},
|
||||
enumerable: true
|
||||
}
|
||||
});
|
||||
_prototypeProperties(Test, null, {
|
||||
test: {
|
||||
get: function () {
|
||||
return 5 + 5;
|
||||
},
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
}
|
||||
});
|
||||
|
||||
return Test;
|
||||
})();
|
||||
|
||||
@@ -1,7 +1,23 @@
|
||||
"use strict";
|
||||
|
||||
var Test = function Test() {};
|
||||
|
||||
Test.prototype.test = function () {
|
||||
return 5 + 5;
|
||||
var _prototypeProperties = function (child, staticProps, instanceProps) {
|
||||
if (staticProps) Object.defineProperties(child, staticProps);
|
||||
if (instanceProps) Object.defineProperties(child.prototype, instanceProps);
|
||||
};
|
||||
|
||||
var Test = (function () {
|
||||
var Test = function Test() {};
|
||||
|
||||
_prototypeProperties(Test, null, {
|
||||
test: {
|
||||
value: function () {
|
||||
return 5 + 5;
|
||||
},
|
||||
writable: true,
|
||||
enumerable: true,
|
||||
configurable: true
|
||||
}
|
||||
});
|
||||
|
||||
return Test;
|
||||
})();
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user