Compare commits

...

264 Commits

Author SHA1 Message Date
Sebastian McKenzie
ca2cbb02f1 v2.6.1 2015-01-06 20:04:54 +11:00
Sebastian McKenzie
b72427cdd0 fix rest parameter tests 2015-01-06 20:04:04 +11:00
Sebastian McKenzie
44e9812ad4 fix rest parameter arguments key - closes #405 2015-01-06 20:02:56 +11:00
Sebastian McKenzie
b7814e5e24 add documentation on optional protoToAssign transformer 2015-01-06 19:58:19 +11:00
Sebastian McKenzie
ec67a83326 add 3.0.0 breaking notes 2015-01-06 18:55:03 +11:00
Sebastian McKenzie
6a560cea25 Merge pull request #404 from thejameskyle/docs
Add new documentation
2015-01-06 18:44:14 +11:00
James Kyle
46f9ed7d74 Add new documentation 2015-01-05 23:27:46 -08:00
Sebastian McKenzie
92366dfc7b move incorrect tag in bug fix to internal 2015-01-06 18:08:42 +11:00
Sebastian McKenzie
f520a46175 better ordering of 2.6.0 changelog groups 2015-01-06 18:08:01 +11:00
Sebastian McKenzie
88bec1196b group 2.6.0 changelog 2015-01-06 18:07:10 +11:00
Sebastian McKenzie
ff0098f3f3 add additional 2.6.0 note 2015-01-06 17:54:34 +11:00
Sebastian McKenzie
d01d7722f4 add dynamic imports note to changelog 2015-01-06 17:49:32 +11:00
Sebastian McKenzie
2845c1a894 v2.6.0 2015-01-06 17:44:13 +11:00
Sebastian McKenzie
ed51728aba remove unused variable 2015-01-06 17:43:26 +11:00
Sebastian McKenzie
4c8f4121f0 add 2.6.0 changelog 2015-01-06 17:41:57 +11:00
Sebastian McKenzie
b9e4340700 better use strict handling inside of modules 2015-01-06 17:32:00 +11:00
Sebastian McKenzie
4c9e39afa1 replace slice with a loop in rest parameters 2015-01-06 17:05:52 +11:00
Sebastian McKenzie
7439247095 change spread call expression context from null to undefined 2015-01-06 16:45:39 +11:00
Sebastian McKenzie
254424ced5 add npm install to make bootstrap 2015-01-06 12:17:39 +11:00
Sebastian McKenzie
4fc6823ece no ast check on api tests 2015-01-06 12:17:29 +11:00
Sebastian McKenzie
d531c8aa4c add expressionStatement around system module wildcard exports 2015-01-06 12:17:20 +11:00
Sebastian McKenzie
fc59f1ff46 add closure around let scoping return tests 2015-01-06 12:16:34 +11:00
Sebastian McKenzie
7c7cd6f9b8 use thisExpression instead of identifier("this") 2015-01-06 12:08:53 +11:00
Sebastian McKenzie
e3174d5a39 add esvalid validation to transformation tests 2015-01-06 12:08:40 +11:00
Sebastian McKenzie
2558a5e12e better wildcard imports and exports - fixes #224 2015-01-06 11:48:23 +11:00
Sebastian McKenzie
7526ae5486 fix register require in transformation helper 2015-01-06 10:45:10 +11:00
Sebastian McKenzie
811fcf7e1b upgrade acorn-6to5 2015-01-06 10:44:13 +11:00
Sebastian McKenzie
62818d468e Merge branch 'traceur' 2015-01-06 10:40:42 +11:00
Sebastian McKenzie
a88bd69e30 justify disabled traceur tests 2015-01-06 10:39:56 +11:00
Sebastian McKenzie
8164bb17ce don't use interopRequire if noInteropRequire is set for default module formatter 2015-01-06 10:39:47 +11:00
Sebastian McKenzie
3ec97fc86d only check if a function is a declaration in common module hoisting 2015-01-06 10:39:18 +11:00
Sebastian McKenzie
b38a00d70e add destructuring defaults #230 2015-01-06 10:38:55 +11:00
Sebastian McKenzie
1b85607d7d add ability to assert just an error instead of an error message in tests 2015-01-06 10:38:28 +11:00
Sebastian McKenzie
fd6704ac25 update optional bluebird coroutine test to reflect new addImport 2015-01-06 10:38:11 +11:00
Sebastian McKenzie
9c527f9d9c make regenerator test use the ALL environment var 2015-01-06 10:37:40 +11:00
Sebastian McKenzie
6cf318d60f add updated interop modules to tests 2015-01-06 10:37:11 +11:00
Sebastian McKenzie
64f9f4dff5 only check declarations in let scoping reference check 2015-01-06 10:36:49 +11:00
Sebastian McKenzie
145413dbfd Merge pull request #396 from caspervonb/master
Add .es to register extensions
2015-01-05 20:55:36 +11:00
Casper Beyer
8c58e0f14c Add .es extension to util.canCompile 2015-01-05 16:43:00 +08:00
Casper Beyer
d62914e41c Amend require documentation to include '.es' extension 2015-01-05 16:35:01 +08:00
Casper Beyer
85db67edf4 Add .es to register extensions
.es is a known ecmascript file extension and should be handled by the loader
See RFC 4329, 8.2.
2015-01-05 16:10:41 +08:00
Sebastian McKenzie
348ad2e25c better dynamic imports - fixes #393 2015-01-05 12:40:12 +11:00
Sebastian McKenzie
5ce8ee6c2b add inheritance type check to tests 2015-01-05 12:39:46 +11:00
Sebastian McKenzie
98ad5d42e1 add optional typeof symbol test options 2015-01-05 12:39:12 +11:00
Sebastian McKenzie
b12734abd6 only run traceur and esnext on ALL_6TO5_TESTS environment variable 2015-01-05 12:39:01 +11:00
Sebastian McKenzie
f34907d518 add make bootstrap 2015-01-05 12:38:34 +11:00
Sebastian McKenzie
3bd6ec20c1 remove regenerator tests and git submodule regenerator 2015-01-05 12:38:26 +11:00
Sebastian McKenzie
b8d4479333 fix linting error 2015-01-05 10:24:23 +11:00
Sebastian McKenzie
ed833be34a force computed property on number literal property 2015-01-05 10:23:30 +11:00
Sebastian McKenzie
16024242b0 add type check to inherits template 2015-01-05 10:23:06 +11:00
Sebastian McKenzie
77add8704e alias hidden properties onto it's transformer instance 2015-01-05 10:22:27 +11:00
Sebastian McKenzie
9fd1ec0596 more reliable toValidIdentifier checking, including reserved words 2015-01-05 10:22:06 +11:00
Sebastian McKenzie
90ce4e93ed don't break let reference checking on loops in let scoping 2015-01-05 10:21:50 +11:00
Sebastian McKenzie
cf7b9234c1 make typeofSymbol transformer optional 2015-01-05 10:21:32 +11:00
Sebastian McKenzie
f85eeeb93c fix blockHoist and declarations transformers unneccesarily unshifting use strict statements 2015-01-05 10:21:24 +11:00
Sebastian McKenzie
45d0eea842 fix native type constructor spread - closes #373 2015-01-05 10:20:36 +11:00
Sebastian McKenzie
b0c9d3daa4 Merge branch 'master' into traceur 2015-01-05 10:19:41 +11:00
Sebastian McKenzie
3f152bfc3f upgrade core-js from 0.3.3 to 0.40 and regenerator from 0.8.2 to 0.8.3 2015-01-05 10:19:01 +11:00
Sebastian McKenzie
ffbfa5281b move esnext tests into their own fixtures folder 2015-01-05 10:18:42 +11:00
Sebastian McKenzie
7f87ca0d43 move traceur test suite to a git submodule 2015-01-05 10:18:30 +11:00
Sebastian McKenzie
a8fad4b958 add traceur gits ubmodule 2015-01-05 10:17:23 +11:00
Sebastian McKenzie
945ea145e7 remove esnext from differences table 2015-01-05 10:17:09 +11:00
Sebastian McKenzie
4f10bcedda Merge pull request #392 from thejameskyle/changlog-tags
Add tags to top of changelog
2015-01-05 10:15:36 +11:00
James Kyle
601b3d584f Add tags to top of changelog 2015-01-04 14:41:17 -08:00
Sebastian McKenzie
42878f85fe Merge pull request #391 from thejameskyle/extend-null-check
Make parent constructor check explicit when extending from null
2015-01-05 09:14:33 +11:00
James Kyle
3b4c9c415e Make parent constructor check explicit when extending from null - fixes #386 2015-01-04 13:45:13 -08:00
Sebastian McKenzie
7345899343 Merge pull request #389 from caspervonb/master
Make build target the default target
2015-01-05 03:01:32 +11:00
Casper Beyer
316102ab14 Make build target the default target
The top target is implicitly the default target, having this as *clean*
is rather unothodox, usually it would be the executable or library target.
2015-01-04 23:53:28 +08:00
Sebastian McKenzie
4c2b85deec better NewExpression paren insertion 2015-01-05 01:06:41 +11:00
Sebastian McKenzie
108784db20 add typeof and interop-require-wildcard helpers 2015-01-05 01:06:28 +11:00
Sebastian McKenzie
a3b30bae7a better traceur test api 2015-01-05 01:06:16 +11:00
Sebastian McKenzie
6420954c53 remove traceur tests 2015-01-05 01:06:07 +11:00
Sebastian McKenzie
a6fda01fa0 Merge branch 'master' into traceur
Conflicts:
	package.json
2015-01-05 00:53:59 +11:00
Sebastian McKenzie
655cc8fcb9 v2.5.0 2015-01-05 00:17:35 +11:00
Sebastian McKenzie
97a504bbef 2.5.0 changelog 2015-01-05 00:16:39 +11:00
Sebastian McKenzie
bf3443962b disable failing esnext tests 2015-01-05 00:15:46 +11:00
Sebastian McKenzie
a4394494ef remove noDuplicateProperties test 2015-01-05 00:15:37 +11:00
Sebastian McKenzie
2b333de81f add basic support for assignment patterns 2015-01-05 00:07:50 +11:00
Sebastian McKenzie
b81f824b7e normalise wildcard import into a default object 2015-01-05 00:07:22 +11:00
Sebastian McKenzie
9bfb8c440a add optional typeof symbol transformer 2015-01-05 00:06:57 +11:00
Sebastian McKenzie
9a6c13a6a4 Merge branch 'esnext'
Conflicts:
	package.json
2015-01-05 00:03:53 +11:00
Sebastian McKenzie
ac8d77fb45 upgrade acorn-6to5 2015-01-04 21:14:59 +11:00
Sebastian McKenzie
09c88238e1 upgrade acorn-6to5 2015-01-04 20:37:14 +11:00
Sebastian McKenzie
103b619364 remove arity traceur test check 2015-01-04 20:36:35 +11:00
Sebastian McKenzie
c8a404fb72 Merge branch 'master' into traceur 2015-01-04 20:26:41 +11:00
Sebastian McKenzie
05669204dd fix generation expression comment tests 2015-01-04 20:26:07 +11:00
Sebastian McKenzie
38e6abec02 Merge branch 'master' into traceur 2015-01-04 20:23:37 +11:00
Sebastian McKenzie
1abef2c1e2 more intelligent parens wrapping of no line terminator expressions - fixes #376, reference #349 2015-01-04 20:22:24 +11:00
Sebastian McKenzie
cc6678361a comment out arity check 2015-01-04 20:20:03 +11:00
Sebastian McKenzie
2587694d44 Merge branch 'master' into traceur
Conflicts:
	package.json
2015-01-04 19:52:52 +11:00
Sebastian McKenzie
f16079c83f v2.4.10 2015-01-04 19:51:52 +11:00
Sebastian McKenzie
b7132f3529 upgrade acorn-6to5 2015-01-04 19:50:54 +11:00
Sebastian McKenzie
ed41f1652e v2.4.9 2015-01-04 19:49:54 +11:00
Sebastian McKenzie
c522bdb4b9 upgrade acorn-6to5 2015-01-04 19:48:47 +11:00
Sebastian McKenzie
005362a615 update tests to 2.4.9 fixes 2015-01-04 19:48:14 +11:00
Sebastian McKenzie
88e542634f fix linting errors 2015-01-04 19:45:18 +11:00
Sebastian McKenzie
c8304138eb add 2.4.9 changelog 2015-01-04 19:44:04 +11:00
Sebastian McKenzie
35608d497e make comprehension for-of loop a let 2015-01-04 19:42:25 +11:00
Sebastian McKenzie
b5a78355c4 add initProps to single call expression in computed property names - fixes #378 2015-01-04 19:42:16 +11:00
Sebastian McKenzie
223e28ba8f upgrade acorn-6to5 2015-01-04 19:40:51 +11:00
Sebastian McKenzie
6a35bdb42b add traceur test suite 2015-01-04 19:40:09 +11:00
Sebastian McKenzie
18813f26bb Merge branch 'master' into esnext 2015-01-04 15:32:41 +11:00
Sebastian McKenzie
ccabb91f69 add back deleted object-define-properties-closure template 2015-01-04 15:30:59 +11:00
Sebastian McKenzie
35fda899a8 remove spec-no-duplicate-properties transformer 2015-01-04 15:30:40 +11:00
Sebastian McKenzie
e2f01d41a3 fix api test 2015-01-04 13:42:16 +11:00
Sebastian McKenzie
931a80f5b3 rename "declarations" to the more sane "helpers" 2015-01-04 13:34:56 +11:00
Sebastian McKenzie
9a2fd22e91 add newline to esnext super change proto test 2015-01-04 08:35:28 +11:00
Sebastian McKenzie
cbcad22d81 update default parameters transformer to use var a = arguments[0] === undefined ? 1 : arguments[0]; instead of if (a === undefined) a = 1; 2015-01-04 08:35:14 +11:00
Sebastian McKenzie
4d5861cfdc remove invalid strict-mode es6 next class test 2015-01-04 08:34:25 +11:00
Sebastian McKenzie
c578db7ae8 upgrade acorn-6to5 2015-01-04 08:34:14 +11:00
Sebastian McKenzie
dea73b7186 change code assertion to 6to5 output 2015-01-04 08:01:29 +11:00
Sebastian McKenzie
4506e39cf5 add toString key to instance keys as methods are enumerable 2015-01-04 08:01:08 +11:00
Sebastian McKenzie
7ab6df093b use Symbol.iterator instead of @@iterator 2015-01-04 08:00:49 +11:00
Sebastian McKenzie
22eeae1a93 use assert instead of expect 2015-01-04 08:00:40 +11:00
Sebastian McKenzie
a645ae0583 contextLiteral fallback in es6-spread transformer 2015-01-04 07:59:56 +11:00
Sebastian McKenzie
7f4efecb7d support for CallExpression in Scope.prototype.generateUidBasedOnNode 2015-01-04 07:59:43 +11:00
Sebastian McKenzie
0c0f40d14a only automatically assume test is exec if it has a js extension 2015-01-04 07:58:49 +11:00
Sebastian McKenzie
cb54c11d84 add esnext tests 2015-01-04 07:39:11 +11:00
Sebastian McKenzie
55123be7d7 use t.toComputedKey in computed property name transformer 2015-01-04 07:38:49 +11:00
Sebastian McKenzie
324a0b408a add optional protoToAssign transformer 2015-01-04 07:38:36 +11:00
Sebastian McKenzie
8b2788e930 fix es6-property-method-assignment tests name 2015-01-03 21:48:22 +11:00
Sebastian McKenzie
d945379b5b remove isDynamic checks and always execute those expressions **once** 2015-01-03 21:48:06 +11:00
Sebastian McKenzie
5a622ac9c7 update traversal api in optional-bluebird-coroutines transformer 2015-01-03 20:11:21 +11:00
Sebastian McKenzie
0e9eac610b rename es5-property-methods-assignment to es6-property-method-assignment and add function ids to object methods and remap them if they contain a reference to themselves - fixes #308 2015-01-03 20:11:00 +11:00
Sebastian McKenzie
1de94a2705 fix code styling on es6 arrow functions nested test 2015-01-03 20:09:14 +11:00
Sebastian McKenzie
71132c3538 add types.toComputedPropertyKey helper 2015-01-03 20:08:39 +11:00
Sebastian McKenzie
d20ab0eb05 rename traverse stop method to skip and add a stop method that actually breaks the current traversal 2015-01-03 20:08:31 +11:00
Sebastian McKenzie
51f7e75d2e fix formatting of code of conduct paragraph in CONTRIBUTING.md 2015-01-03 11:17:55 +11:00
Sebastian McKenzie
ab4b5ce994 Merge pull request #309 from antn/add-code-of-conduct
add code of conduct
2015-01-03 11:16:05 +11:00
Sebastian McKenzie
f0d50ca9a2 add browser.js to package.json 2015-01-03 08:19:18 +11:00
Sebastian McKenzie
5168355a64 fix differences copytext grammar 2015-01-03 08:19:11 +11:00
Sebastian McKenzie
2f209a9e4e v2.4.8 2015-01-03 07:37:15 +11:00
Sebastian McKenzie
20695eaba6 add 2.4.8 changelog 2015-01-03 07:36:34 +11:00
Sebastian McKenzie
340a4dd1f2 fix code styling #370 2015-01-03 07:35:45 +11:00
Sebastian McKenzie
ef1c7a5c69 Merge pull request #370 from hughsk/browserify-register
Make require("6to5/register") work with browserify
2015-01-03 07:33:15 +11:00
Hugh Kennedy
5a01beaa1f Make require("6to5/register") work with browserify
Previously, you'd have to create a separate file for using 6to5
with both node and browserify, as the latter wasn't able to properly
handle loading 6to5's dependency tree and would crash on attempting
to do so.

This change instructs browserify to use "register-browser.js" in place
of "register.js". "register-browser.js" still loads the 6to5 polyfill,
but is otherwise ignored.
2015-01-02 21:30:40 +01:00
Sebastian McKenzie
5a5bf7b4ac v2.4.7 2015-01-03 06:10:52 +11:00
Sebastian McKenzie
88ee15bb4d upgrade acorn-6to5 #367 2015-01-03 06:10:10 +11:00
Sebastian McKenzie
3e51b65095 v2.4.6 2015-01-03 05:29:28 +11:00
Sebastian McKenzie
371df9ad09 add 2.4.6 changelog 2015-01-03 05:25:48 +11:00
Sebastian McKenzie
d43d5ff409 move coreAliasing and undefinedToVoid transformers down 2015-01-03 05:24:43 +11:00
Sebastian McKenzie
c2c8e52430 add modules caveat - fixes #368 2015-01-03 05:23:12 +11:00
Sebastian McKenzie
57c0ebc5f4 v2.4.5 2015-01-02 22:22:52 +11:00
Sebastian McKenzie
339bf82481 avoid printing comments if they've already been output - fixes #365 2015-01-02 22:22:01 +11:00
Sebastian McKenzie
d981c06444 v2.4.4 2015-01-02 19:24:56 +11:00
Sebastian McKenzie
8269e1488b fix incorrect scripts reference in browser 2015-01-02 19:23:50 +11:00
Sebastian McKenzie
ddda7a020f add 2.4.4 changelog 2015-01-02 19:22:03 +11:00
Sebastian McKenzie
7e9340864a lowercase object rest/spread feature name in doc/index 2015-01-02 19:20:14 +11:00
Sebastian McKenzie
5ec19f23c3 add test skeleton for types and add jsdoc comments to types 2015-01-02 19:20:05 +11:00
Sebastian McKenzie
ba48b66458 add types.appendToMemberExpression and types.prependToMemberExpression helpers 2015-01-02 16:46:58 +11:00
Sebastian McKenzie
6e8c73f65f fix incorrect member expression properties 2015-01-02 16:39:35 +11:00
Sebastian McKenzie
b34fcb0cd9 split up method binding and add description for memoization assignment operator 2015-01-02 14:33:51 +11:00
Sebastian McKenzie
ff7129f1aa remove ES5 methods from caveats and change IE classes note to IE 10 and below 2015-01-02 14:33:38 +11:00
Sebastian McKenzie
fbabd193a4 add module type to 6to5 browser 2015-01-02 14:33:18 +11:00
Sebastian McKenzie
876d69798c v2.4.3 2015-01-02 05:19:42 +11:00
Sebastian McKenzie
1a963ddc06 remove unused variable 2015-01-02 05:19:00 +11:00
Sebastian McKenzie
beb5acea6b better addImport with good hoisting etc 2015-01-02 05:18:03 +11:00
Sebastian McKenzie
6a290f233e add 2.4.3 changelog 2015-01-02 05:01:18 +11:00
Sebastian McKenzie
74563d88ed upgrade acorn-6to5 2015-01-02 05:00:23 +11:00
Sebastian McKenzie
a18177026c add support for statements in asyncToGenerator and bluebirdCoroutines transformers 2015-01-02 04:58:59 +11:00
Sebastian McKenzie
a813341433 v2.4.2 2015-01-02 04:25:44 +11:00
Sebastian McKenzie
4968de9803 fix linting errors 2015-01-02 04:24:56 +11:00
Sebastian McKenzie
0de2d33e8d add 2.4.2 changelog 2015-01-02 04:24:19 +11:00
Sebastian McKenzie
6f81ddd0d5 upgrade acorn-6to5 2015-01-02 04:24:19 +11:00
Sebastian McKenzie
6b83055b12 alias flat references in coreAliasing transformer 2015-01-02 04:24:19 +11:00
Sebastian McKenzie
080c23d5ed Merge pull request #360 from mquandalle/patch-1
Extend the license to the new year
2015-01-02 04:06:22 +11:00
Sebastian McKenzie
293bec58d7 remove appveyor badge 2015-01-02 03:53:33 +11:00
Sebastian McKenzie
93ceafc732 better uid names 2015-01-02 03:53:28 +11:00
Sebastian McKenzie
b2bac04b72 update object getter memoization docs to reflect new changes 2015-01-02 03:04:26 +11:00
Sebastian McKenzie
e549c37ca1 v2.4.1 2015-01-02 03:00:33 +11:00
Sebastian McKenzie
02512da38d fix generation tests with parenthesized expressions and trailing comments 2015-01-02 02:59:53 +11:00
Sebastian McKenzie
abe9c4fd30 add 2.4.1 changelog 2015-01-02 02:57:16 +11:00
Sebastian McKenzie
af21c52cc6 set generator on correct node #252 2015-01-02 02:55:55 +11:00
Sebastian McKenzie
706626f79a better whitespace handling of parenthesized comments due to trailing comments 2015-01-02 02:55:40 +11:00
Sebastian McKenzie
b8dd421073 v2.4.0 2015-01-02 02:26:14 +11:00
Sebastian McKenzie
5453c466d6 remove unused variable 2015-01-02 02:24:49 +11:00
Sebastian McKenzie
0cfb2e76b8 add 2.4.0 changelog 2015-01-02 02:24:01 +11:00
Sebastian McKenzie
ba67f57c1e use simple loops always in array comprehensions, support yield inside of array comprehensions - closes #325, fixes #252 2015-01-02 02:14:36 +11:00
Sebastian McKenzie
f1a178f8f9 compact body nodes in traversal 2015-01-02 01:59:49 +11:00
Sebastian McKenzie
b1d1909c64 forced closure on super classes - fixes #339 2015-01-02 01:59:42 +11:00
Sebastian McKenzie
9529f93690 move useStrict transformer to after _moduleFormatter 2015-01-02 01:58:56 +11:00
Sebastian McKenzie
925b1f7600 add optional asyncToGenerator transformer - closes #321 2015-01-02 01:31:14 +11:00
Sebastian McKenzie
40f8bc0a65 add optional bluebird coroutine transformer - @phpnode 2015-01-02 01:20:28 +11:00
Sebastian McKenzie
3a0dbabf5a v2.3.2 2015-01-02 01:04:43 +11:00
Sebastian McKenzie
383912c11b more reliable t.isExpression 2015-01-02 01:04:04 +11:00
Sebastian McKenzie
470c8fced0 add parens on expressions with trailing comments - fixes #349 2015-01-02 00:57:48 +11:00
Sebastian McKenzie
e3dc2355e8 v2.3.1 2015-01-02 00:46:14 +11:00
Sebastian McKenzie
9733cb58c9 remove unused variable 2015-01-02 00:45:26 +11:00
Sebastian McKenzie
edd5a3878a fix redefined variables 2015-01-02 00:45:01 +11:00
Sebastian McKenzie
78d2c4fa8d 2.3.1 changelog 2015-01-02 00:43:54 +11:00
Sebastian McKenzie
e268dc6138 return Object.defineProperties without a closure in property methods assignment unless it's really necessary 2015-01-02 00:42:28 +11:00
Sebastian McKenzie
5b6c0fcacd add whitespace after array and object expressions 2015-01-02 00:41:58 +11:00
Sebastian McKenzie
777f2be14e add undefinedToVoid optional transformer 2015-01-02 00:41:33 +11:00
Sebastian McKenzie
41d60a85e9 simplify define property by using a helper in playground object getter memoization 2015-01-02 00:40:47 +11:00
Sebastian McKenzie
800c350db6 use Object.defineProperty on computed properties - fixes #357 2015-01-02 00:40:37 +11:00
Sebastian McKenzie
7b5b8ab6ed add undefinedToVoid optional transformer 2015-01-02 00:25:17 +11:00
Maxime Quandalle
c7a02ca289 Extend the license to the new year 2015-01-01 13:03:38 +01:00
Sebastian McKenzie
52e23473ed allow export default non-functions mapping to module.exports in common module formatter - fixes #356 2015-01-01 22:58:46 +11:00
Sebastian McKenzie
af412cae28 v2.3.0 2015-01-01 22:40:44 +11:00
Sebastian McKenzie
4c2c96366f add 2.3.0 changelog 2015-01-01 22:40:02 +11:00
Sebastian McKenzie
de427936a6 remove invalid lval super classes in generation tests 2015-01-01 22:38:01 +11:00
Sebastian McKenzie
9d6850d576 fix linting errors 2015-01-01 22:35:08 +11:00
Sebastian McKenzie
20a0280a52 add support for optional transformers 2015-01-01 22:35:02 +11:00
Sebastian McKenzie
64b7d6fa93 more verbose unknown node error message in code generator 2015-01-01 22:34:51 +11:00
Sebastian McKenzie
d7ca7ebbb9 remove Transformer exposure 2015-01-01 22:34:29 +11:00
Sebastian McKenzie
9680730e24 remove forced closure on super classes 2015-01-01 22:34:22 +11:00
Sebastian McKenzie
07667d80ff clean up traverse 2015-01-01 22:34:05 +11:00
Sebastian McKenzie
9a633ebd9c update scope to use new traversal api 2015-01-01 22:33:40 +11:00
Sebastian McKenzie
fac4a61245 use Makefile command shortcuts 2015-01-01 22:33:30 +11:00
Sebastian McKenzie
0ebc073762 update traversal api, removing return false; in favor of this.stop(); 2015-01-01 22:33:17 +11:00
Sebastian McKenzie
860432cdfd hoist export default to very top 2015-01-01 22:31:59 +11:00
Sebastian McKenzie
c408432445 add support for circular references and hoist all variable declarations 2015-01-01 22:30:28 +11:00
Sebastian McKenzie
27e9f9d616 remove invalid lval super class test 2015-01-01 22:29:57 +11:00
Sebastian McKenzie
94a11cd602 add optional core aliasing transformer 2015-01-01 20:02:20 +11:00
Sebastian McKenzie
ab6e424cac make experimental transformers declare that they're experimental 2015-01-01 20:01:24 +11:00
Sebastian McKenzie
9ee7b07cbf add corejs aliasing transformer and support for optional transformers 2015-01-01 20:01:09 +11:00
Sebastian McKenzie
31fff092b6 upgrade acorn-6to5 - fixes #358 and #353 2014-12-31 11:56:04 +11:00
Sebastian McKenzie
e847ac11af add object-getter-memoization template 2014-12-31 11:54:51 +11:00
Sebastian McKenzie
aee1ca45b0 add isFalsyExpression check to superName and make classes a closure if they're inheriting 2014-12-31 11:54:39 +11:00
Sebastian McKenzie
46632e1a97 better object getter memoization - closes #353 2014-12-31 11:54:13 +11:00
Sebastian McKenzie
961e0b9b6b reenable system modules tests 2014-12-31 11:51:52 +11:00
Sebastian McKenzie
afdde8b3a7 v2.2.0 2014-12-29 12:48:45 +11:00
Sebastian McKenzie
918ddb4124 disable system tests temporairly 2014-12-29 11:16:47 +11:00
Sebastian McKenzie
18739ad78b remove unused variable 2014-12-29 11:15:24 +11:00
Sebastian McKenzie
74a84e2473 fix duplicate comments being output, breaking code 2014-12-29 11:13:50 +11:00
Sebastian McKenzie
52ffc65a06 make system module formatter modules anonymous by default - fixes #347 2014-12-29 01:55:30 +11:00
Sebastian McKenzie
d4fbfbbe47 Merge pull request #348 from guybedford/system
System test adjustments
2014-12-29 01:51:16 +11:00
Sebastian McKenzie
781467d423 v2.1.0 2014-12-29 01:41:05 +11:00
Sebastian McKenzie
44f5b7d013 fix case statement newline in code generator test 2014-12-29 01:39:04 +11:00
Sebastian McKenzie
dcf7f0b70b fix newline in case statement test 2014-12-29 01:37:19 +11:00
Sebastian McKenzie
03efd69998 check if node exists before inheriting comments to it 2014-12-29 01:37:12 +11:00
Sebastian McKenzie
213003a007 fix new templates path in dotfiles 2014-12-29 01:34:49 +11:00
Sebastian McKenzie
b0503f2efe add 2.1.0 changelog 2014-12-29 01:33:58 +11:00
Sebastian McKenzie
c8cf7ff286 better blacklist tests and expose register cache - closes #344 2014-12-29 01:31:26 +11:00
Sebastian McKenzie
ceb32816d7 fix destructuring in switch/case statements - closes #346 2014-12-29 01:26:51 +11:00
Sebastian McKenzie
32b94899a6 update runtime script to runtime generator 2014-12-29 01:26:21 +11:00
Sebastian McKenzie
d951082b09 move replacement node comment inheritance to traverse replacement 2014-12-29 01:26:11 +11:00
Sebastian McKenzie
b49f6e33d6 fix newline on case statement 2014-12-29 01:25:56 +11:00
Sebastian McKenzie
c5fa6425a5 explicit canRun for hidden transformers 2014-12-29 01:25:15 +11:00
Sebastian McKenzie
70d896d609 rename runtime script to runtime-generator 2014-12-29 01:24:57 +11:00
Sebastian McKenzie
e00fa8c9b1 update core-js 2014-12-29 01:24:41 +11:00
Sebastian McKenzie
13933bc9b8 move templates folder into transformation folder 2014-12-29 01:24:35 +11:00
guybedford
295bab544b re-exporting in setters 2014-12-28 14:43:56 +02:00
guybedford
cfe05ca10d exported variable declarations hoist along with functions 2014-12-28 14:41:32 +02:00
guybedford
da72182219 make modules anonymous 2014-12-28 14:38:52 +02:00
Sebastian McKenzie
005f5b2174 v2.0.4 2014-12-28 11:06:04 +11:00
Sebastian McKenzie
8551c94fa0 fix linting errors 2014-12-28 11:05:27 +11:00
Sebastian McKenzie
c509d06bc2 vaoid being greedy when destructuring array iterables 2014-12-28 11:04:00 +11:00
Sebastian McKenzie
f21743012b v2.0.3 2014-12-28 09:37:32 +11:00
Sebastian McKenzie
22dc33f93c remove unused variable 2014-12-28 09:36:29 +11:00
Sebastian McKenzie
6df6652629 better circular references in amd/umd/system module formatter 2014-12-28 09:35:47 +11:00
Sebastian McKenzie
4942ba6dd7 v2.0.2 2014-12-28 01:14:54 +11:00
Sebastian McKenzie
b63bd8cba0 remove interopRequire from system module formatter 2014-12-28 01:14:08 +11:00
Sebastian McKenzie
cd1eb11171 Merge branch 'master' of github.com:6to5/6to5 2014-12-28 01:10:00 +11:00
Sebastian McKenzie
6e1c12fd78 inherit comments in for-of transformer 2014-12-28 01:09:48 +11:00
Sebastian McKenzie
a4ea71b85d Merge pull request #337 from guybedford/master
Correct system format base support tests
2014-12-28 01:03:35 +11:00
Sebastian McKenzie
1df69bdbeb v2.0.1 2014-12-28 01:02:29 +11:00
Sebastian McKenzie
84c2766756 remove unused variable 2014-12-28 01:01:52 +11:00
Sebastian McKenzie
1f000ac83d add 2.0.1 changelog 2014-12-28 01:01:18 +11:00
Sebastian McKenzie
322aa246b8 fix automatic closure on private declarations - fixes #335 2014-12-28 01:01:13 +11:00
Sebastian McKenzie
601bbb86cd remap UpdateExpression in module exports - closes #334 2014-12-28 01:00:53 +11:00
guybedford
5c39685650 correct system format base support tests 2014-12-27 15:59:52 +02:00
antn
f4055612e5 add link to code of conduct [ci skip] 2014-12-16 22:29:37 -08:00
antn
46911bd28c add code of conduct 2014-12-16 22:17:35 -08:00
521 changed files with 6644 additions and 4323 deletions

6
.gitmodules vendored Normal file
View File

@@ -0,0 +1,6 @@
[submodule "vendor/traceur"]
path = vendor/traceur
url = https://github.com/google/traceur-compiler
[submodule "vendor/regenerator"]
path = vendor/regenerator
url = https://github.com/facebook/regenerator

View File

@@ -1,3 +1,3 @@
node_modules
test
lib/6to5/templates
lib/6to5/transformation/templates

View File

@@ -1,7 +1,7 @@
node_modules
*.log
*.cache
lib/6to5/templates
lib/6to5/transformation/templates
test
benchmark
Makefile

View File

@@ -1,6 +1,156 @@
# Changelog
Gaps between patch versions are faulty/broken releases.
> **Tags:**
> - [New Feature]
> - [Bug Fix]
> - [Spec Compliancy]
> - [Breaking Change]
> - [Documentation]
> - [Internal]
> - [Polish]
_Note: Gaps between patch versions are faulty/broken releases._
## 2.6.1
* **Bug Fix**
* Fix rest parameter arguments key.
## 2.6.0
* **Bug Fix**
* Better handling of number literal property keys.
* Handle `NewExpression` paren insertion edegcases better.
* **Internal**
* Fix incorrect AST node `identifier("this")`.
* Better `toIdentifier` method that handles reserved words.
* Upgrade `acorn-6to5`.
* Fix exponentiation operator precedence.
* Fix line terminators after async contextual keywords.
* Add semicolons as class elements inside of a class body.
* Upgrade to `core-js` 4.0.0.
* Upgrade to `regenerator` 0.8.3.
* Fix non-loop labeled statements.
* **New Feature**
* Basic destructuring defaults
* Add `.es` to list of supported extensions.
* Add optional `typeofSymbol` transformer.
* Use a `for` loop for rest parameters instead of `Array.prototype.slice`.
* **Polish**
* Move `"use strict";` to inside module bodies instead of at the top of the file.
* Better handling of dynamic imports.
* **Spec Compliancy**
* Class inheritance now has a `function` or `null` type check.
* Add `interopRequireWildcard` around wildcard imports and exports to handle non-object exports.
## 2.5.0
* Remove `noDuplicateProperties` transformer.
* Better generated UIDs based on nodes.
* Default parameters now use `arguments[i]`, conditionals and variable declarations instead of using long-form if statements.
## 2.4.10
* Upgrade `acorn-6to5`.
## 2.4.9
* Upgrade `acorn-6to5`.
* Add optional `protoToAssign` transformer.
* Fix missing properties from computed property keys.
* Make ES7 comprehensions `let` variables.
## 2.4.8
* Make `require("6to5/register")` work with browserify - [#370](https://github.com/6to5/6to5/pull/370). Thanks [@hughsk](https://github.com/hughsk)!
## 2.4.7
* Upgrade `acorn-6to5`.
## 2.4.6
* Move `coreAliasing` and `undefinedToVoid` transformers down to catch `moduleFormatter` transforms.
## 2.4.5
* Avoid printing comments if they've already been output.
## 2.4.4
* Add `module` type to browser build `<script>` handler.
* Fix some `MemberExpression` modifying incorrectly setting `property` to a `MemberExpression`.
## 2.4.3
* Upgrade `acorn-6to5`.
* Add support for `FunctionDeclaration`s in `bluebirdCoroutines` and `asyncToGenerators` transformers.
## 2.4.2
* Upgrade `acorn-6to5`.
* Better uids generated for various transformers based on parent node.
* Alias flat references in `coreAliasing` transformer.
## 2.4.1
* Better whitespace handling of parenthesized expressions due to trailing comments.
* Fix `yield` inside of comprehensions.
## 2.4.0
* Use a closure always for classes with a super.
* Always use native loops for array comprehensions.
* Allow `yield` inside of comprehensions.
* Add optional `bluebirdCoroutine` transformer.
* Add optional `asyncToGenerator` transformer.
* Move `useStrict` transformer to before `_moduleFormatter` causing `"use strict";` to always be placed the very top.
## 2.3.2
* Add parens on expressions with trailing comments.
## 2.3.1
* Add `undefinedToVoid` optional transformer.
* Use `Object.defineProperty` for computed properties.
## 2.3.0
* Upgrade `acorn-6to5`.
* Support circular references and hoist variable declarations in `system` module formatter.
* Add optional transformers, including a new `coreAliasing` transformer that aliases native ES6 static properties to their `core-js` equivalent.
## 2.2.0
* Make `system` module formatter modules anonymous by default.
* Fix duplicate comments being output, breaking code.
## 2.1.0
* Add `cache` option to register hook.
* Update `core-js`.
* Fix starting newline not being added on case statements.
* Fix destructuring `VariableDeclaration`s not inside `BlockStatement`s and `Program`.
## 2.0.4
* Avoid being greedy when destructuring array iterables.
## 2.0.3
* Hoist function declarations in system module formatter for circular references.
* Hoist default function declarations in umd and amd module formatters for circular references.
## 2.0.2
* Inherit comments in `for-of` transformer.
* Remove `interopRequire` from `system` module formatter.
## 2.0.1
* Remap `UpdateExpression` module export binding.
* Fix automatic closure on `PrivateDeclaration` in classes.
## 2.0.0

13
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,13 @@
# Contributor Code of Conduct
As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion.
Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)

View File

@@ -1,5 +1,7 @@
# Contributing
Before contributing, please read the [code of conduct](https://github.com/6to5/6to5/blob/master/CODE_OF_CONDUCT.md).
* **General**
* No ES6 syntax features or methods, exclusively ES5.
* Max of five arguments for functions

View File

@@ -1,4 +1,4 @@
Copyright (c) 2014 Sebastian McKenzie
Copyright (c) 2014-2015 Sebastian McKenzie
MIT License

View File

@@ -6,46 +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
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
test-clean:
rm -rf test/tmp
test:
make lint
$(MOCHA_CMD)
make test-clean
test-cov:
rm -rf coverage
node $(ISTANBUL_CMD) $(MOCHA_CMD) --
test-spec:
node $(ISTANBUL_CMD) $(MOCHA_CMD) -- --reporter spec
test-travis:
make test-spec
if test -n "$$CODECLIMATE_REPO_TOKEN"; then codeclimate < coverage/lcov.info; fi
test-browser:
mkdir -p dist
node bin/cache-templates
node bin/cache-tests
node $(BROWSERIFY_CMD) -e test/_browser.js >dist/6to5-test.js
rm -rf templates.json tests.json
test -n "`which open`" && open test/browser.html
.PHONY: clean test test-cov test-clean lint test-travis test-spec test-browser publish bench build bootstrap
build:
mkdir -p dist
@@ -63,6 +24,43 @@ build:
rm -rf templates.json
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
test-clean:
rm -rf test/tmp
test: lint
$(MOCHA_CMD)
make test-clean
test-cov:
rm -rf coverage
node $(ISTANBUL_CMD) $(MOCHA_CMD) --
test-spec:
node $(ISTANBUL_CMD) $(MOCHA_CMD) -- --reporter spec
test-travis: test-spec
if test -n "$$CODECLIMATE_REPO_TOKEN"; then codeclimate < coverage/lcov.info; fi
test-browser:
mkdir -p dist
node bin/cache-templates
node bin/cache-tests
node $(BROWSERIFY_CMD) -e test/_browser.js >dist/6to5-test.js
rm -rf templates.json tests.json
test -n "`which open`" && open test/browser.html
publish:
git pull --rebase
@@ -83,3 +81,8 @@ publish:
git push --follow-tags
rm -rf templates.json browser.js runtime.js browser-polyfill.js
bootstrap:
npm install
git submodule update --init
cd vendor/regenerator; npm install

8
NOTES.md Normal file
View File

@@ -0,0 +1,8 @@
# Notes
* Wildcard exports/imports wont normalise if `export default` is a non-object.
## 3.0.0 breaking changes
* Remove `allowImportExportEverywhere` option from acorn.
* Remove this shorthand from playground.

View File

@@ -11,10 +11,6 @@
<img alt="Travis Status" src="http://img.shields.io/travis/6to5/6to5/master.svg?style=flat&amp;label=travis">
</a>
<a href="https://ci.appveyor.com/project/sebmck/6to5">
<img alt="Appveyor Status" src="http://img.shields.io/appveyor/ci/sebmck/6to5.svg?style=flat&amp;label=appveyor">
</a>
<a href="https://codeclimate.com/github/6to5/6to5">
<img alt="Code Climate Score" src="http://img.shields.io/codeclimate/github/6to5/6to5.svg?style=flat">
</a>

View File

@@ -1,4 +1,4 @@
#!/usr/bin/env node
var runtime = require("../lib/6to5/runtime");
var runtime = require("../lib/6to5/runtime-generator");
console.log(runtime(process.argv[2]));

View File

@@ -17,18 +17,28 @@ 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("-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("-a, --amd-module-ids", "Insert module id in AMD modules", false);
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.on("--help", function(){
var outKeys = function (title, obj) {
console.log(" " + title + ":");
console.log();
var hasOptional = true;
_.each(_.keys(obj).sort(), function (key) {
if (key[0] === "_") return;
if (obj[key].optional) {
hasOptional = true;
key = "[" + key + "]";
}
console.log(" - " + key);
});
@@ -89,12 +99,13 @@ if (errors.length) {
exports.opts = {
sourceMapName: commander.outFile,
amdModuleIds: commander.amdModuleIds,
experimental: commander.experimental,
playground: commander.playground,
moduleIds: commander.amdModuleIds || commander.moduleIds,
blacklist: commander.blacklist,
whitelist: commander.whitelist,
sourceMap: commander.sourceMaps || commander.sourceMapsInline,
optional: commander.optional,
comments: !commander.removeComments,
runtime: commander.runtime,
modules: commander.modules

View File

@@ -1,65 +0,0 @@
# Browser
A browser version of 6to5 is available from `browser.js` inside the 6to5
directory in an npm release.
## Scripts
While it's not recommended for serious use, when the browser version is included
all scripts with the type `text/ecmascript-6` and `text/6to5` are automatically
compiled and ran.
For example:
```html
<script src="node_modules/6to5/browser.js"></script>
<script type="text/6to5">
class Test {
test() {
return "test";
}
}
var test = new Test;
test.test();
</script>
```
## Build
You can build a browser version of the compiler by running the following in the
6to5 directory:
```sh
$ make build
```
This will output the files `dist/6to5.js` and `dist/6to5.min.js`.
## Test
To test 6to5 in your browser run:
```sh
$ make test-browser
```
And open `test/browser.html` in your browser if it doesn't open automatically.
## API
### to5.transform(code, [opts])
See [options](usage.md#options) for additional documentation.
```javascript
to5.transform("class Test {}").code;
```
### to5.run(code, [opts])
See [options](usage.md#options) for additional documentation.
```javascript
to5.run("class Test {}");
```

View File

@@ -1,4 +1,12 @@
# Caveats
---
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
@@ -9,12 +17,15 @@ You may alternatively selectively include what you need:
| Feature | Requirements |
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| Abstract References | [experimental](experimental.md), `Symbol` |
| Array destructuring | `Array.isArray`, `Array.from` |
| 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.isArray`, `Array.from` |
| 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.isArray`, `Array.from` |
| Spread | `Array.from` |
*Only required for exporting a non-function `default` with additional `export`s.
## ES5
@@ -26,34 +37,53 @@ ES5 such as lower versions of IE then using the
## Internet Explorer
### Classes (9 and below)
### 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 <= 9 so static properties
**will not** be inherited. A possible workaround is to use `super();`:
**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
class Foo {
static foo() {
}
}
class Bar extends Foo {
static foo() {
super();
}
}
require("6to5").transform("code", { optional: ["protoToAssign"] });
```
## Getters/setters (8 and below)
```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).
**Reference**: [MDN](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty#Internet_Explorer_8_specific_notes).

View File

@@ -1,6 +1,12 @@
# Differences
---
layout: docs
title: Compare
description: Differences between 6to5 and other ES6 transpilers.
permalink: /docs/compare/
redirect_from: /differences.html
---
There are three main points that separate 6to5 from all other transpilers.
## Differences
### Readable code
@@ -12,13 +18,13 @@ is concerned with making sure it works **and** is readable at the same time.
For example, given the following array comprehension:
```javascript
```js
var seattlers = [for (c of customers) if (c.city == "Seattle") { name: c.name, age: c.age }];
```
is generated to the following with 6to5:
```javascript
```js
var seattlers = Array.from(customers).filter(function (c) {
return c.city == "Seattle";
}).map(function (c) {
@@ -31,7 +37,7 @@ var seattlers = Array.from(customers).filter(function (c) {
The following is what Traceur generates:
```javascript
```js
var seattlers = (function() {
var c;
var $__20 = 0,
@@ -49,13 +55,12 @@ var seattlers = (function() {
}());
```
As you can tell, it's not very pretty, unreadable even. Instead of mapping
directly to a runtime, like other transpilers, 6to5 maps directly to the
equivalent ES5.
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
are bother you then you can use the [optional runtime](optional-runtime.md).
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.
@@ -79,43 +84,43 @@ that when you turn it off and use your code in a full ES6 environment
### Features
| | 6to5 | Traceur | es6-transpiler | esnext | es6now | jstransform |
| ---------------------------- | ---- | ------- | -------------- | ------ | ------ | ----------- |
| Source maps | ✓ | ✓ | ✓ | ✓ | | ✓ |
| No compiler global pollution | ✓ | | ✓ | ✓ | | ✓ |
| Optional runtime | ✓ | | ✓ | | | ✓ |
| Browser compiler | ✓ | ✓ | | ✓ | | |
| | 6to5 | Traceur | es6-transpiler | es6now | jstransform |
| ---------------------------- | ---- | ------- | -------------- | ------ | ----------- |
| Source maps | ✓ | ✓ | ✓ | | ✓ |
| No compiler global pollution | ✓ | | ✓ | | ✓ |
| Optional runtime | ✓ | | ✓ | | ✓ |
| Browser compiler | ✓ | ✓ | | | |
### Language Support
| | 6to5 | Traceur | es6-transpiler | esnext | 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 | ✓ | ✓ | ✓ | | | |
| | 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)

View File

@@ -1,8 +0,0 @@
## Experimental
6to5 also has experimental support for ES7 proposals. You can enable this with
the `experimental: true` option when using the [Node API](#node) or
`--experimental` when using the [CLI](#cli).
**WARNING:** These proposals are subject to change so use with
**extreme caution**.

View File

@@ -1,283 +0,0 @@
# Features
## Abstract references ([experimental](experimental.md)) ([spec](https://github.com/zenparsing/es-abstract-refs))
```javascript
foo::bar;
foo::bar = baz;
delete foo::bar;
```
## Array comprehensions ([experimental](experimental.md))
```javascript
var results = [for (c of customers) if (c.city == "Seattle") { name: c.name, age: c.age }]
```
## Arrow functions
```javascript
// 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);
});
}
};
```
## Async functions ([experimental](experimental.md)) ([spec](https://github.com/lukehoban/ecmascript-asyncawait))
```javascript
async function chainAnimationsAsync(elem, animations) {
for (var anim of animations) {
await anim(elem);
}
}
```
## Async generator functions ([experimental](experimental.md)) ([spec](https://github.com/jhusain/asyncgenerator))
```javascript
```
## Classes
```javascript
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();
}
}
```
## Computed property names
```javascript
var foo = "foo";
var bar = "bar";
var obj = {
["foo" + bar]: "heh",
["bar" + foo]: "noo",
foo: "foo",
bar: "bar"
};
```
## Constants
```javascript
const MULTIPLIER = 5;
console.log(2 * MULTIPLIER);
MULTIPLIER = 6; // error
var MULTIPLIER; // error
```
## Default parameters
```javascript
function f(x, y = 12) {
// y is 12 if not passed (or passed as undefined)
return x + y;
}
f(3) == 15
```
## Destructuring
```javascript
// 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;
```
## Exponentiation operator ([experimental](experimental.md)) ([spec](https://github.com/rwaldron/exponentiation-operator))
```javascript
var a = 2;
a **= 2;
var squared = 2 ** 2;
```
## For-of
```javascript
for (var i of [1, 2, 3]) {
console.log(i * i);
}
```
## Generators
```javascript
function* fibonacci() {
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;
console.log(n);
}
```
## Generator comprehensions ([experimental](experimental.md))
```javascript
var nums = [1, 2, 3, 4, 5, 6];
var multiples = (for (i of nums) if (i % 2) i * i);
assert.equal(multiples.next().value, 1);
assert.equal(multiples.next().value, 9);
assert.equal(multiples.next().value, 25);
```
## Let scoping
```javascript
for (let i in arr) {
let v = arr[i];
}
```
## Modules
```javascript
import "foo";
import foo from "foo";
import * as foo from "foo";
import {bar} from "foo";
import {foo as bar} from "foo";
export { test };
export var test = 5;
export function test() {}
export default test;
```
## Numeric literals
```javascript
0b111110111 === 503; // true
0o767 === 503; // true
```
## Object spread/rest ([experimental](experimental.md)) ([spec](https://github.com/sebmarkbage/ecmascript-rest-spread))
```javascript
var n = { x, y, ...z };
var { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
```
## Property method assignment
```javascript
var obj = {
foo() {
return "foobar";
},
get bar() {
return this._bar;
},
set bar(val) {
this._bar = val;
}
};
```
## Property name shorthand
```javascript
function f(x, y) {
return { x, y };
}
```
## Rest parameters
```javascript
function f(x, ...y) {
// y is an Array
return x * y.length;
}
f(3, "hello", true) == 6
```
## Spread
```javascript
function f(x, y, z) {
return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6
```
## Template literals
```javascript
var x = 5;
var y = 10;
console.log(`${x} + ${y} = ${x + y}`); // "5 + 10 = 15"
```
## Unicode regex
```javascript
var string = 'foo💩bar';
var match = string.match(/foo(.)bar/u);
console.log(match[1]);
```

View File

@@ -1,62 +0,0 @@
**6to5** turns ES6+ code into vanilla ES5, so you can use next generation features **today.**
- **Readable** - formatting is retained if possible so your generated code is as similar as possible.
- **Extensible** - with a large range of [plugins](plugins.md) and **browser support**.
- **Lossless** - **source map support** so you can debug your compiled code with ease.
- **Compact** - maps directly to the equivalent ES5 with **no runtime**[\*](caveats.md).
## Installation
It's as easy as:
$ npm install -g 6to5
## Usage
Once you've installed 6to5, there are multiple paths you can take depending on
how you want to use it.
6to5 will simply compile your ES6+ script to ES5 if you pass it as an argument
to the command-line tool `6to5`:
```sh
$ 6to5 script.js
```
If you have a file written using ES6+ and you just want to run it, `6to5-node`
has you covered:
```sh
$ 6to5-node script.js
```
And it doesn't end here! To see all the ways you can use 6to5, check out the
[Usage](http://6to5.github.io/usage.html) page.
## [Features](features.md)
- [Abstract references](features.md#abstract-references) ([experimental](experimental.md))
- [Array comprehension](features.md#array-comprehension) ([experimental](experimental.md))
- [Async functions](features.md#async-functions) ([experimental](experimental.md))
- [Async generator functions](features.md#async-generator-functions) ([experimental](experimental.md))
- [Arrow functions](features.md#arrow-functions)
- [Classes](features.md#classes)
- [Computed property names](features.md#computed-property-names)
- [Constants](features.md#constants)
- [Default parameters](features.md#default-parameters)
- [Destructuring](features.md#destructuring)
- [Exponentiation operator](features.md#exponentiation-operator) ([experimental](experimental.md))
- [For-of](features.md#for-of)
- [Generators](features.md#generators)
- [Generator comprehension](features.md#generator-comprehension) ([experimental](experimental.md))
- [Let scoping](features.md#let-scoping)
- [Modules](features.md#modules)
- [Numeric literals](features.md#numeric-literals)
- [Object Rest/Spread](features.md#object-rest-spread) ([experimental](experimental.md))
- [Property method assignment](features.md#property-method-assignment)
- [Property name shorthand](features.md#property-name-shorthand)
- [React/JSX](react.md)
- [Rest parameters](features.md#rest-parameters)
- [Spread](features.md#spread)
- [Template literals](features.md#template-literals)
- [Unicode regex](features.md#unicode-regex)

View File

@@ -1,120 +0,0 @@
# Playground
Playground is a proving ground for **possible** ES7 proposals.
**NOTE: These features are in no way endorsed by Ecma International and are not a part of ES6. They might become a part of ECMAScript in the future.**
## Usage
$ 6to5 --playground
```javascript
to5.transform("code", { playground: true });
```
**NOTE:** Enabling `playground` also enables [experimental support](experimental.md).
## Features
* [Memoization operator](#memoization-operator)
* [Method binding](#method-binding)
* [Object getter memoization](#object-getter-memoization)
* [This shorthand](#this-shorthand)
### Memoization assignment operator
```javascript
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
```
```javascript
var obj = {};
obj.x ?= 2;
```
equivalent to:
```javascript
var obj = {};
if (!Object.prototype.hasOwnProperty.call(obj, "x")) obj.x = 2;
```
### Method binding
```javascript
var fn = obj#method;
var fn = obj#method("foob");
["foo", "bar"].map(#toUpperCase); // ["FOO", "BAR"]
[1.1234, 23.53245, 3].map(#toFixed(2)); // ["1.12", "23.53", "3.00"]
```
equivalent to:
```javascript
var fn = obj.method.bind(obj);
var fn = obj.method.bind(obj, "foob");
["foo", "bar"].map(function (val) { return val.toUpperCase(); });
[1.1234, 23.53245, 3].map(function (val) { return val.toFixed(2); });
```
### Object getter memoization
```javascript
var foo = {
memo bar() {
return complex();
}
};
class Foo {
memo bar() {
return complex();
}
}
```
equivalent to
```javascript
var foo = {
get bar() {
if (this._barRan) return this._bar;
this._barRan = true;
return this._bar = complex();
}
};
class Foo {
get bar() {
if (this._barRan) return this._bar;
this._barRan = true;
return this._bar = complex();
}
}
```
**NOTE:** Memoised functions will return the result of the **first** execution, regardless of arguments.
### This shorthand
```javascript
@foo
```
equivalent to
```javascirpt
this.foo
```

View File

@@ -1,33 +0,0 @@
# Plugins
## Build systems
- [Broccoli](https://github.com/6to5/broccoli-6to5-transpiler)
- [Browserify](https://github.com/6to5/6to5ify)
- [Brunch](https://github.com/6to5/6to5-brunch)
- [Duo](https://github.com/6to5/duo6to5)
- [Gobble](https://github.com/6to5/gobble-6to5)
- [Gulp](https://github.com/6to5/gulp-6to5)
- [Grunt](https://github.com/6to5/grunt-6to5)
- [Sprockets](https://github.com/josh/sprockets-es6) or via [Browserify](https://github.com/6to5/6to5-rails)
- [webpack](https://github.com/6to5/6to5-loader)
## Integrations
- [Isparta](https://github.com/douglasduteil/isparta) - Code coverage with `karma` and `instanbul` using 6to5
- [JSXHint](https://github.com/STRML/JSXHint) - A wrapper around JSHint to allow linting of JSX files
## Bridges
- [Ruby](https://github.com/6to5/6to5-ruby)
## Testing
- [Jest](https://github.com/6to5/6to5-jest)
- [Karma](https://github.com/6to5/karma-6to5-preprocessor)
- [Mocha](https://github.com/6to5/6to5-mocha)
## Misc
- [Connect](https://github.com/6to5/6to5-connect)
- [Jade](https://github.com/6to5/jade-6to5)

View File

@@ -1,34 +0,0 @@
# Polyfill
6to5 includes a polyfill that includes a custom
[regenerator runtime](https://github.com/facebook/regenerator/blob/master/runtime.js) and
[core.js](https://github.com/zloirock/core-js).
This will emulate a full ES6 environment. This polyfill is automatically loaded
when using [6to5-node](usage.md#node) and [6to5/register](usage.md#register-hook).
## Usage
### Node/Browserify
You need to include the polyfill require at the top the **entry point** to your
application.
```javascript
require("6to5/polyfill");
```
Fortunately, this is automatically loaded when using:
```javascript
require("6to5/register");
```
### 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`.

View File

@@ -1,17 +0,0 @@
# React/JSX
6to5 has built-in support for React v0.12. Tags are automatically transformed to
their equivalent `React.createElement(...)` and `displayName` is automatically
inferred and added to all `React.createClass` calls.
## Blacklist
To disable this behaviour add `react` to your blacklist:
```javascript
to5.transform("code", { blacklist: ["react"] });
```
```sh
$ 6to5 --blacklist react
```

708
doc/setup.md Normal file
View File

@@ -0,0 +1,708 @@
---
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">&#8984; + 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 Normal file
View File

@@ -0,0 +1,771 @@
---
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`. Dont 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-keyd 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>

View File

@@ -1,255 +0,0 @@
# Usage
## CLI
Compile the file `script.js` and output it to stdout.
```sh
$ 6to5 script.js
```
Compile the file `script.js` and output it to `script-compiled.js`.
```sh
$ 6to5 script.js --out-file script-compiled.js
```
Compile the file `script.js` and output it to `script-compiled.js` and save a
source map to `script-compiled.js.map`.
```sh
$ 6to5 script.js --source-maps --out-file script-compiled.js
```
Compile the file `script.js` and output it to `script-compiled.js` with a source
map embedded in a comment at the bottom.
```sh
$ 6to5 script.js --source-maps-inline --out-file script-compiled.js
```
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
```
Pipe a file in via stdin and output it to `script-compiled.js`
```sh
$ 6to5 --out-file script-compiled.js < script.js
```
### Node
Launch a repl.
```sh
$ 6to5-node
```
Evaluate code.
```sh
$ 6to5-node -e "class Test { }"
```
Compile and run `test.js`.
```sh
$ 6to5-node test
```
## Node
```javascript
var to5 = require("6to5");
```
### to5.transform(code, [opts]);
```javascript
var result = to5.transform("code();", options);
result.code;
result.map;
result.ast;
```
### to5.transformFileSync(filename, [opts])
```javascript
to5.transformFileSync("filename.js", options).code;
```
### to5.transformFile(filename, [opts], callback)
```javascript
to5.transformFile("filename.js", options, function (err, result) {
result.code;
});
```
### to5.transform.fromAst(ast, [code], [opts])
```javascript
var result = to5.transform.fromAst(ast, "var a = 2;", opts);
result.code;
result.map;
result.ast;
```
#### Options
```javascript
{
// Filename for use in errors etc.
// Default: "unknown"
filename: "filename",
// Filename relative to `sourceRoot`
// Default: `filename` option.
filenameRelative: "",
// List of transformers to EXCLUDE.
// Run `6to5 --help` to see a full list of transformers.
blacklist: [],
// List of transformers to ONLY use.
// Run `6to5 --help` to see a full list of transformers.
whitelist: [],
// Module formatter to use
// Run `6to5 --help` to see a full list of module formatters.
// Default: "common"
modules: "common",
// 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.
// Default: false
sourceMap: true,
// Set `file` on returned source map.
// Default: `filenameRelative` option.
sourceMapName: "filename",
// Set `sources[0]` on returned source map.
// Default: `filenameRelative` option.
sourceFileName: "filename",
// The root from which all sources are relative
// Default: `moduleRoot` option.
sourceRoot: "assets/scripts",
// Optional prefix for the AMD module formatter that will be prepend to the
// filename on module definitions
// Default: `sourceRoot` option.
moduleRoot: "my-app",
// If truthy, insert an explicit id for each defined AMD module.
// By default, AMD modules are anonymous.
// Default: false
amdModuleIds: true,
// Optionally replace all 6to5 helper declarations with a referenece to this
// variable. If set to `true` then the default namespace is used "to5Runtime".
// Default: false
runtime: true,
// Enable support for experimental ES7 features
// Default: false
experimental: true,
// Set this to `false` if you don't want the transformed AST in the returned
// result
// Default: true
ast: true,
// Set this to `false` if you don't want the transformed code in the returned
// result
// Default: true
code: true,
format: {
// Output comments in generated output
// Default: true
comments: true,
// Do not include superfluous whitespace characters and line terminators
// Default: false
compact: false,
indent: {
// Preserve parentheses in new expressions that have no arguments
// Default: true
parentheses: true,
// Adjust the indentation of multiline comments to keep asterisks vertically aligned
// Default: true
adjustMultilineComment: true,
// Indent string
// Default: " "
style: " ",
// Base indent level
// Default: 0
base: 0
}
}
}
```
### Require hook
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; but this is automatically loaded when using:
Source maps are automatically configured so if any errors a thrown then line
number info is mapped and you'll get the correct source location.
```javascript
require("6to5/register");
```
**NOTE:** By default all requires to `node_modules` will be ignored. You can
override this by passing an ignore regex via:
```javascript
require("6to5/register")({
// This will override `node_modules` ignoring - you can alternatively pass
// a regex
ignore: false
});
```
**NOTE:** Using 6to5-node or `require("6to5/register")`, 6to5 will check what features are available in the current environment and blacklists them if they're supported.
#### 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"]
});
```

59
doc/usage/api.md Normal file
View File

@@ -0,0 +1,59 @@
---
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;
```

59
doc/usage/browser.md Normal file
View File

@@ -0,0 +1,59 @@
---
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 {}');
````

99
doc/usage/cli.md Normal file
View File

@@ -0,0 +1,99 @@
---
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
```

28
doc/usage/experimental.md Normal file
View File

@@ -0,0 +1,28 @@
---
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 });
```

22
doc/usage/jsx.md Normal file
View File

@@ -0,0 +1,22 @@
---
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
```

View File

@@ -1,37 +1,39 @@
# Modules
---
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
### CLI
```sh
$ 6to5 --modules common script.js
```
### Node
```javascript
var to5 = require("6to5");
```js
to5.transform('import "foo";', { modules: "common" });
```
## Formats
* [AMD](#amd)
* [Common (Default)](#common-default)
* [Ignore](#ignore)
* [System](#system)
* [UMD](#umd)
### Common (Default)
### Common
**Usage**
```sh
$ 6to5 --modules common
```
**In**
**Example**
```javascript
```js
export default test;
export {test};
@@ -46,9 +48,7 @@ import {bar} from "foo";
import {foo as bar} from "foo";
```
**Out**
```javascript
```js
"use strict";
var _interopRequire = function (obj) {
@@ -72,13 +72,15 @@ var bar = require("foo").foo;
### AMD
**Usage**
```sh
$ 6to5 --modules amd
```
**In**
**Example**
```javascript
```js
import foo from "foo";
export function bar() {
@@ -86,9 +88,7 @@ export function bar() {
}
```
**Out**
```javascript
```js
define(["exports", "foo"], function (exports, _foo) {
"use strict";
@@ -105,21 +105,24 @@ define(["exports", "foo"], function (exports, _foo) {
});
```
You can optionally specify to include the module id (using the `--amd-module-id` argument):
You can optionally specify to include the module id (using the `--amd-module-id`
argument):
```javascript
```js
define("filename", ["exports", "foo"], function (exports, _foo) {})
```
### UMD
### System
**Usage**
```sh
$ 6to5 --modules umd
$ 6to5 --modules system
```
**In**
**Example**
```javascript
```js
import foo from "foo";
export function bar() {
@@ -127,9 +130,46 @@ export function bar() {
}
```
**Out**
```js
System.register("bar", ["foo"], function (_export) {
"use strict";
```javascript
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);
@@ -154,13 +194,15 @@ export function bar() {
### Ignore
**Usage**
```sh
$ 6to5 --modules ignore
```
**In**
**Example**
```javascript
```js
import foo from "foo";
export function bar() {
@@ -168,69 +210,30 @@ export function bar() {
}
```
**Out**
```javascript
```js
function bar() {
return foo("foobar");
}
```
### System
```sh
$ 6to5 --modules system
```
**In**
```javascript
import foo from "foo";
export function bar() {
return foo("foobar");
}
```
**Out**
```javascript
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);
}
};
});
```
## Custom
### Custom
You can alternatively specify module names instead of one of the built-in types.
```sh
**Usage**
```js
$ 6to5 --modules custom-module-formatter
```
**node_modules/custom-module-formatter/index.js**
**Example**
```javascript
**`node_modules/custom-module-formatter/index.js`**
```js
module.exports = ModuleFormatter;
function ModuleFormatter() {
}
function ModuleFormatter() {}
ModuleFormatter.prototype.transform = function (ast) {
// this is ran after all transformers have had their turn at modifying the ast

35
doc/usage/options.md Normal file
View File

@@ -0,0 +1,35 @@
---
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. |

173
doc/usage/playground.md Normal file
View File

@@ -0,0 +1,173 @@
---
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
```

56
doc/usage/polyfill.md Normal file
View File

@@ -0,0 +1,56 @@
---
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>

55
doc/usage/require.md Normal file
View File

@@ -0,0 +1,55 @@
---
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']
});
```

View File

@@ -1,4 +1,11 @@
# Optional runtime
---
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
@@ -8,25 +15,17 @@ 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.
Simply use the following option if you're using the [Node API](usage.md#node):
## Usage
```javascript
{
runtime: true
}
```
or the following flag if you're using the [CLI](usage.md#cli):
```ssh
```js
$ 6to5 --runtime
```
Then just include the runtime before your generated code.
```js
to5.transform('code', { runtime: true });
```
## Getting the runtime
You can get the runtime via either:
### Getting the runtime
```sh
$ 6to5-runtime
@@ -34,24 +33,24 @@ $ 6to5-runtime
or
```javascript
require("6to5").runtime();
```js
require('6to5').runtime();
```
or from an npm release in `runtime.js` from the 6to5 directory.
## Customising namespace
### Customising namespace
You can also customise the runtime namespace by passing an optional namespace
argument:
```javascript
require("6to5").runtime("myCustomNamespace");
```
```sh
$ 6to5-runtime myCustomNamespace
```
See [Options - runtime](usage.md#options) for documentation on changing the
reference in generated code.
```js
require("6to5").runtime('myCustomNamespace');
```
See [Options - runtime](../options) for documentation on changing the reference in
generated code.

View File

@@ -34,7 +34,7 @@ transform.load = function (url, callback, opts, hold) {
var runScripts = function () {
var scripts = [];
var types = ["text/ecmascript-6", "text/6to5"];
var types = ["text/ecmascript-6", "text/6to5", "module"];
var index = 0;
var exec = function () {
@@ -60,8 +60,9 @@ var runScripts = function () {
}
};
var _scripts = global.document.getElementsByTagName("script");
for (var i in _scripts) {
var _scripts = global.document .getElementsByTagName("script");
for (var i = 0; i < _scripts.length; ++i) {
var _script = _scripts[i];
if (types.indexOf(_script.type) >= 0) scripts.push(_script);
}

View File

@@ -10,21 +10,37 @@ var t = require("./types");
var _ = require("lodash");
function File(opts) {
this.opts = File.normaliseOptions(opts);
this.uids = {};
this.ast = {};
this.dynamicImports = [];
this.dynamicImportIds = {};
this.opts = File.normaliseOptions(opts);
this.transformers = this.getTransformers();
this.uids = {};
this.ast = {};
}
File.declarations = [
File.helpers = [
"inherits",
"defaults",
"prototype-properties",
"apply-constructor",
"tagged-template-literal",
"interop-require",
"to-array",
"sliced-to-array",
"object-without-properties",
"has-own",
"slice"
"slice",
"bind",
"define-property",
"async-to-generator",
"interop-require-wildcard",
"typeof",
"exports-wildcard"
];
File.excludeHelpersFromRuntime = [
"async-to-generator",
"typeof"
];
File.normaliseOptions = function (opts) {
@@ -34,9 +50,11 @@ File.normaliseOptions = function (opts) {
experimental: false,
playground: false,
whitespace: true,
moduleIds: opts.amdModuleIds || false,
blacklist: [],
whitelist: [],
sourceMap: false,
optional: [],
comments: true,
filename: "unknown",
modules: "common",
@@ -78,17 +96,46 @@ File.normaliseOptions = function (opts) {
transform._ensureTransformerNames("blacklist", opts.blacklist);
transform._ensureTransformerNames("whitelist", opts.whitelist);
transform._ensureTransformerNames("optional", opts.optional);
return opts;
};
File.prototype.toArray = function (node) {
File.prototype.getTransformers = function () {
var file = this;
var transformers = [];
var secondPassTransformers = [];
_.each(transform.transformers, function (transformer) {
if (transformer.canRun(file)) {
transformers.push(transformer);
if (transformer.secondPass) {
secondPassTransformers.push(transformer);
}
if (transformer.manipulateOptions) {
transformer.manipulateOptions(file.opts, file);
}
}
});
return transformers.concat(secondPassTransformers);
};
File.prototype.toArray = function (node, i) {
if (t.isArrayExpression(node)) {
return node;
} else if (t.isIdentifier(node) && node.name === "arguments") {
return t.callExpression(t.memberExpression(this.addDeclaration("slice"), t.identifier("call")), [node]);
return t.callExpression(t.memberExpression(this.addHelper("slice"), t.identifier("call")), [node]);
} else {
return t.callExpression(this.addDeclaration("to-array"), [node]);
var declarationName = "to-array";
var args = [node];
if (i) {
args.push(t.literal(i));
declarationName = "sliced-to-array";
}
return t.callExpression(this.addHelper(declarationName), args);
}
};
@@ -119,8 +166,24 @@ File.prototype.parseShebang = function (code) {
return code;
};
File.prototype.addDeclaration = function (name) {
if (!_.contains(File.declarations, name)) {
File.prototype.addImport = function (source, name) {
name = name || source;
var id = this.dynamicImportIds[name];
if (!id) {
id = this.dynamicImportIds[name] = this.generateUidIdentifier(name);
var specifiers = [t.importSpecifier(t.identifier("default"), id)];
var declar = t.importDeclaration(specifiers, t.literal(source));
declar._blockHoist = 3;
this.dynamicImports.push(declar);
}
return id;
};
File.prototype.addHelper = function (name) {
if (!_.contains(File.helpers, name)) {
throw new ReferenceError("unknown declaration " + name);
}
@@ -131,7 +194,7 @@ File.prototype.addDeclaration = function (name) {
var ref;
var runtimeNamespace = this.opts.runtime;
if (runtimeNamespace) {
if (runtimeNamespace && !_.contains(File.excludeHelpersFromRuntime, name)) {
name = t.identifier(t.toIdentifier(name));
return t.memberExpression(t.identifier(runtimeNamespace), name);
} else {
@@ -174,15 +237,25 @@ File.prototype.parse = function (code) {
};
File.prototype.transform = function (ast) {
var self = this;
this.ast = ast;
this.scope = new Scope(ast.program);
this.moduleFormatter = this.getModuleFormatter(this.opts.modules);
var self = this;
var astRun = function (key) {
_.each(self.transformers, function (transformer) {
transformer.astRun(self, key);
});
};
_.each(transform.transformers, function (transformer) {
astRun("enter");
_.each(this.transformers, function (transformer) {
transformer.transform(self);
});
astRun("exit");
};
File.prototype.generate = function () {
@@ -215,7 +288,7 @@ File.prototype.generate = function () {
};
File.prototype.generateUid = function (name, scope) {
name = t.toIdentifier(name);
name = t.toIdentifier(name).replace(/^_+/, "");
scope = scope || this.scope;

View File

@@ -115,6 +115,7 @@ CodeGenerator.prototype.print = function (node, parent, opts) {
if (!node) return "";
var self = this;
opts = opts || {};
var newline = function (leading) {
@@ -147,6 +148,12 @@ CodeGenerator.prototype.print = function (node, parent, opts) {
};
if (this[node.type]) {
var needsNoLineTermParens = n.needsParensNoLineTerminator(node, parent);
var needsParens = needsNoLineTermParens || n.needsParens(node, parent);
if (needsParens) this.push("(");
if (needsNoLineTermParens) this.indent();
this.printLeadingComments(node, parent);
newline(true);
@@ -154,13 +161,12 @@ CodeGenerator.prototype.print = function (node, parent, opts) {
if (opts.before) opts.before();
this.map.mark(node, "start");
// only compute if this node needs parens if our parent has been changed
// since acorn would've wrapped us in a ParanthesizedExpression
var needsParens = n.needsParens(node, parent);
if (needsParens) this.push("(");
this[node.type](node, this.buildPrint(node), parent);
if (needsNoLineTermParens) {
this.newline();
this.dedent();
}
if (needsParens) this.push(")");
this.map.mark(node, "end");
@@ -170,7 +176,7 @@ CodeGenerator.prototype.print = function (node, parent, opts) {
this.printTrailingComments(node, parent);
} else {
throw new ReferenceError("unknown node " + node.type);
throw new ReferenceError("unknown node of type " + JSON.stringify(node.type) + " with constructor " + JSON.stringify(node && node.constructor.name));
}
};
@@ -268,14 +274,21 @@ CodeGenerator.prototype._printComments = function (comments) {
var self = this;
_.each(comments, function (comment) {
var skip = false;
// find the original comment in the ast and set it as displayed
_.each(self.ast.comments, function (origComment) {
if (origComment.start === comment.start) {
// comment has already been output
if (origComment._displayed) skip = true;
origComment._displayed = true;
return false;
}
});
if (skip) return;
// whitespace before
self.newline(self.whitespace.getNewlinesBefore(comment));

View File

@@ -1,5 +1,6 @@
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
exports.UnaryExpression = function (node, print) {
var hasSpace = /[a-z]$/.test(node.operator);
@@ -86,6 +87,7 @@ exports.ExpressionStatement = function (node, print) {
exports.BinaryExpression =
exports.LogicalExpression =
exports.AssignmentPattern =
exports.AssignmentExpression = function (node, print) {
print(node.left);
this.push(" " + node.operator + " ");
@@ -98,7 +100,16 @@ exports.MemberExpression = function (node, print) {
var obj = node.object;
print(obj);
if (node.computed) {
if (!node.computed && t.isMemberExpression(node.property)) {
throw new TypeError("Got a MemberExpression for MemberExpression property");
}
var computed = node.computed;
if (t.isLiteral(node.property) && _.isNumber(node.property.value)) {
computed = true;
}
if (computed) {
this.push("[");
print(node.property);
this.push("]");

View File

@@ -146,7 +146,7 @@ exports.SwitchCase = function (node, print) {
this.push("default:");
}
this.space();
this.newline();
print.sequence(node.consequent, { indent: true });
};

View File

@@ -61,14 +61,40 @@ Node.prototype.needsParens = function () {
if (!parent) return false;
if (t.isNewExpression(parent) && parent.callee === node) {
return t.isCallExpression(node) || _.some(node, function (val) {
if (t.isCallExpression(node)) return true;
var hasCall = _.some(node, function (val) {
return t.isCallExpression(val);
});
if (hasCall) return true;
}
return find(parens, node, parent);
};
Node.prototype.needsParensNoLineTerminator = function () {
var parent = this.parent;
var node = this.node;
if (!parent) return false;
// no comments
if (!node.leadingComments || !node.leadingComments.length) {
return false;
}
if (t.isYieldExpression(parent) || t.isAwaitExpression(parent)) {
return true;
}
if (t.isContinueStatement(parent) || t.isBreakStatement(parent) ||
t.isReturnStatement(parent) || t.isThrowStatement(parent)) {
return true;
}
return false;
};
_.each(Node.prototype, function (fn, key) {
Node[key] = function (node, parent) {
var n = new Node(node, parent);

View File

@@ -13,15 +13,30 @@ _.each([
["<", ">", "<=", ">=", "in", "instanceof"],
[">>", "<<", ">>>"],
["+", "-"],
["*", "/", "%"]
["*", "/", "%"],
["**"]
], function (tier, i) {
_.each(tier, function (op) {
PRECEDENCE[op] = i;
});
});
exports.ObjectExpression = function (node, parent) {
if (t.isExpressionStatement(parent)) {
// ({ foo: "bar" });
return true;
}
if (t.isMemberExpression(parent) && parent.object === node) {
// ({ foo: "bar" }).foo
return true;
}
return false;
};
exports.Binary = function (node, parent) {
if (t.isCallExpression(parent) && parent.callee === node) {
if ((t.isCallExpression(parent) || t.isNewExpression(parent)) && parent.callee === node) {
return true;
}

View File

@@ -55,6 +55,8 @@ _.each({
Function: 1,
Class: 1,
For: 1,
ArrayExpression: { after: 1 },
ObjectExpression: { after: 1 },
SwitchStatement: 1,
IfStatement: { before: 1 },
CallExpression: { after: 1 },

View File

@@ -3,11 +3,9 @@ var util = require("./util");
var fs = require("fs");
var _ = require("lodash");
exports.Transformer = require("./transformation/transformer");
exports.types = require("./types");
exports.runtime = require("./runtime");
exports.runtime = require("./runtime-generator");
exports.register = function (opts) {
var register = require("./register");

View File

@@ -12,6 +12,12 @@ var types = require("ast-types");
var def = types.Type.def;
var or = types.Type.or;
def("AssignmentPattern")
.bases("Pattern")
.build("left", "right")
.field("left", def("Pattern"))
.field("right", def("Expression"));
// Acorn - Same as ImportNamespaceSpecifier but `id` is `name`
def("ImportBatchSpecifier")
.bases("Specifier")

View File

@@ -0,0 +1,4 @@
// Required to safely use 6to5/register within a browserify codebase.
module.exports = function () {};
require("./polyfill");

View File

@@ -1,6 +1,7 @@
require("./polyfill");
var sourceMapSupport = require("source-map-support");
var roadrunner = require("roadrunner");
var util = require("./util");
var to5 = require("./index");
var fs = require("fs");
@@ -38,15 +39,22 @@ var blacklistTest = function (transformer, code) {
};
blacklistTest("arrayComprehension", "var foo = [for (foo of bar) foo * foo];");
//blacklistTest("generatorComprehension", "");
blacklistTest("generatorComprehension", "var foo = (for (foo of bar) foo * foo)");
blacklistTest("arrowFunctions", "var foo = x => x * x;");
blacklistTest("classes", "class Foo {}");
blacklistTest("computedPropertyNames", "var foo = { [foo]: bar };");
//blacklistTest("constants", "const foo = 0;");
blacklistTest("constants", function () {
try {
new Function("const foo = 'foo';\nfoo = 'wow';");
} catch (err) {
return; // constants are supported
}
throw new SyntaxError;
});
blacklistTest("defaultParamaters", "var foo = function (bar = 0) {};");
blacklistTest("destructuring", "var { x, y } = { x: 0, y: 0 };");
blacklistTest("forOf", "for (var foo of bar) {}");
blacklistTest("generators", "function* foo() {}");
blacklistTest("generators", "function* foo() {}\nasync function bar() {}"); // generators/async functions delegated to same transformer
blacklistTest("letScoping", "let foo = 0;");
blacklistTest("modules", 'import foo from "from";');
blacklistTest("propertyMethodAssignment", "{ get foo() {} }");
@@ -115,7 +123,7 @@ var hookExtensions = function (_exts) {
});
};
hookExtensions([".es6", ".js"]);
hookExtensions([".es6", ".es", ".js"]);
module.exports = function (opts) {
// normalise options
@@ -130,6 +138,11 @@ module.exports = function (opts) {
if (opts.cache) cache = opts.cache;
if (opts.cache === false) cache = null;
if (opts.cache === true) {
roadrunner.load();
roadrunner.setup();
cache = roadrunner.get("6to5");
}
_.extend(transformOpts, opts);
};

View File

@@ -18,7 +18,11 @@ module.exports = function (namespace) {
)
]));
_.each(File.declarations, function (name) {
_.each(File.helpers, function (name) {
if (_.contains(File.excludeHelpersFromRuntime, name)) {
return false;
}
var key = t.identifier(t.toIdentifier(name));
body.push(t.expressionStatement(
t.assignmentExpression("=", t.memberExpression(namespace, key), util.template(name))

View File

@@ -1,5 +0,0 @@
ARRAY.filter(function (KEY) {
return FILTER;
}).map(function (KEY) {
return STATEMENT;
});

View File

@@ -1,3 +0,0 @@
ARRAY.map(function (KEY) {
return STATEMENT;
});

View File

@@ -1,5 +0,0 @@
(function (obj) {
for (var i in obj) {
exports[i] = obj[i];
}
})(OBJECT);

View File

@@ -1,3 +0,0 @@
(function (KEY) {
return KEY;
})(OBJECT)

View File

@@ -1 +0,0 @@
if (VARIABLE === undefined) VARIABLE = DEFAULT;

View File

@@ -1 +0,0 @@
var VARIABLE_NAME = require(MODULE_NAME);

View File

@@ -44,16 +44,42 @@ DefaultFormatter.prototype.remapAssignments = function () {
var self = this;
var isLocalReference = function (node, scope) {
var left = node.left;
var name = left.name;
return t.isIdentifier(left) && localExports[name] && localExports[name] === scope.get(name, true);
var name = node.name;
return t.isIdentifier(node) && localExports[name] && localExports[name] === scope.get(name, true);
};
traverse(this.file.ast, {
enter: function (node, parent, scope) {
if (t.isExportDeclaration(node)) return false;
if (t.isUpdateExpression(node) && isLocalReference(node.argument, scope)) {
this.skip();
if (t.isAssignmentExpression(node) && isLocalReference(node, scope)) {
// expand to long file assignment expression
var assign = t.assignmentExpression(node.operator[0] + "=", node.argument, t.literal(1));
// remap this assignment expression
var remapped = self.remapExportAssignment(assign);
// we don't need to change the result
if (t.isExpressionStatement(parent) || node.prefix) {
return remapped;
}
var nodes = [];
nodes.push(remapped);
var operator;
if (node.operator === "--") {
operator = "+";
} else { // "++"
operator = "-";
}
nodes.push(t.binaryExpression(operator, node.argument, t.literal(1)));
return t.sequenceExpression(nodes);
}
if (t.isAssignmentExpression(node) && isLocalReference(node.left, scope)) {
this.skip();
return self.remapExportAssignment(node);
}
}
@@ -98,9 +124,9 @@ DefaultFormatter.prototype._pushStatement = function (ref, nodes) {
return ref;
};
DefaultFormatter.prototype._hoistExport = function (declar, assign) {
DefaultFormatter.prototype._hoistExport = function (declar, assign, priority) {
if (t.isFunctionDeclaration(declar)) {
assign._blockHoist = true;
assign._blockHoist = priority || 2;
}
return assign;
@@ -113,24 +139,32 @@ DefaultFormatter.prototype._exportSpecifier = function (getRef, specifier, node,
if (node.source) {
if (t.isExportBatchSpecifier(specifier)) {
// export * from "foo";
nodes.push(this._exportsWildcard(getRef()));
nodes.push(this._exportsWildcard(getRef(), node));
} else {
var ref;
if (t.isSpecifierDefault(specifier.id) || this.noInteropRequire) {
ref = t.memberExpression(getRef(), specifier.id);
} else {
ref = t.callExpression(this.file.addHelper("interop-require"), [getRef()]);
}
// export { foo } from "test";
nodes.push(this._exportsAssign(
t.getSpecifierName(specifier),
t.memberExpression(getRef(), specifier.id)
ref,
node
));
}
} else {
// export { foo };
nodes.push(this._exportsAssign(t.getSpecifierName(specifier), specifier.id));
nodes.push(this._exportsAssign(t.getSpecifierName(specifier), specifier.id, node));
}
};
DefaultFormatter.prototype._exportsWildcard = function (objectIdentifier) {
return util.template("exports-wildcard", {
OBJECT: objectIdentifier
}, true);
return t.expressionStatement(t.callExpression(this.file.addHelper("exports-wildcard"), [
t.callExpression(this.file.addHelper("interop-require-wildcard"), [objectIdentifier])
]));
};
DefaultFormatter.prototype._exportsAssign = function (id, init) {
@@ -143,30 +177,36 @@ DefaultFormatter.prototype._exportsAssign = function (id, init) {
DefaultFormatter.prototype.exportDeclaration = function (node, nodes) {
var declar = node.declaration;
var id = declar.id;
if (node.default) {
nodes.push(
this._exportsAssign(t.identifier("default"), this._pushStatement(declar, nodes))
);
} else {
var assign;
id = t.identifier("default");
}
if (t.isVariableDeclaration(declar)) {
for (var i in declar.declarations) {
var decl = declar.declarations[i];
var assign;
decl.init = this._exportsAssign(decl.id, decl.init).expression;
if (t.isVariableDeclaration(declar)) {
for (var i in declar.declarations) {
var decl = declar.declarations[i];
var newDeclar = t.variableDeclaration(declar.kind, [decl]);
if (i === "0") t.inherits(newDeclar, declar);
nodes.push(newDeclar);
}
} else {
assign = this._exportsAssign(declar.id, declar.id);
decl.init = this._exportsAssign(decl.id, decl.init, node).expression;
nodes.push(t.toStatement(declar));
nodes.push(assign);
this._hoistExport(declar, assign);
var newDeclar = t.variableDeclaration(declar.kind, [decl]);
if (i === "0") t.inherits(newDeclar, declar);
nodes.push(newDeclar);
}
} else {
var ref = declar;
if (t.isFunctionDeclaration(declar) || t.isClassDeclaration(declar)) {
ref = declar.id;
nodes.push(declar);
}
assign = this._exportsAssign(id, ref, node);
nodes.push(assign);
this._hoistExport(declar, assign);
}
};

View File

@@ -5,8 +5,8 @@ var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
function AMDFormatter(file) {
this.file = file;
function AMDFormatter() {
DefaultFormatter.apply(this, arguments);
this.ids = {};
}
@@ -55,7 +55,7 @@ AMDFormatter.prototype.transform = function (ast) {
*/
AMDFormatter.prototype.getModuleName = function () {
if (this.file.opts.amdModuleIds) {
if (this.file.opts.moduleIds) {
return DefaultFormatter.prototype.getModuleName.apply(this, arguments);
} else {
return null;
@@ -83,9 +83,9 @@ AMDFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
if (t.isImportBatchSpecifier(specifier)) {
// import * as bar from "foo";
} else if (t.isSpecifierDefault(specifier)) {
} else if (t.isSpecifierDefault(specifier) && !this.noInteropRequire) {
// import foo from "foo";
ref = t.callExpression(this.file.addDeclaration("interop-require"), [ref]);
ref = t.callExpression(this.file.addHelper("interop-require"), [ref]);
} else {
// import {foo} from "foo";
ref = t.memberExpression(ref, specifier.id, false);

View File

@@ -26,24 +26,30 @@ CommonJSFormatter.prototype.importSpecifier = function (specifier, node, nodes)
if (t.isSpecifierDefault(specifier)) {
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(variableName,
t.callExpression(this.file.addDeclaration("interop-require"), [util.template("require", {
t.callExpression(this.file.addHelper("interop-require"), [util.template("require", {
MODULE_NAME: node.source
})])
)
]));
} else {
// import foo from "foo";
var templateName = "require-assign";
// import * as bar from "foo";
if (specifier.type !== "ImportBatchSpecifier") templateName += "-key";
nodes.push(util.template(templateName, {
VARIABLE_NAME: variableName,
MODULE_NAME: node.source,
KEY: specifier.id
}));
if (specifier.type === "ImportBatchSpecifier") {
// import * as bar from "foo";
nodes.push(t.variableDeclaration("var", [
t.variableDeclarator(
variableName,
t.callExpression(this.file.addHelper("interop-require-wildcard"), [
t.callExpression(t.identifier("require"), [node.source])
])
)
]));
} else {
// import foo from "foo";
nodes.push(util.template("require-assign-key", {
VARIABLE_NAME: variableName,
MODULE_NAME: node.source,
KEY: specifier.id
}));
}
}
};
@@ -57,6 +63,7 @@ CommonJSFormatter.prototype.importDeclaration = function (node, nodes) {
CommonJSFormatter.prototype.exportDeclaration = function (node, nodes) {
if (node.default) {
var declar = node.declaration;
var assign;
// module.exports = VALUE;
var templateName = "exports-default-module";
@@ -64,15 +71,29 @@ CommonJSFormatter.prototype.exportDeclaration = function (node, nodes) {
// exports = module.exports = VALUE;
if (this.hasNonDefaultExports) templateName = "exports-default-module-override";
var assign = util.template(templateName, {
VALUE: this._pushStatement(declar, nodes)
}, true);
if (t.isFunctionDeclaration(declar) || !this.hasNonDefaultExports) {
assign = util.template(templateName, {
VALUE: this._pushStatement(declar, nodes)
}, true);
// hoist to the top if this default is a function
nodes.push(this._hoistExport(declar, assign));
} else {
DefaultFormatter.prototype.exportDeclaration.apply(this, arguments);
// hoist to the top if this default is a function
nodes.push(this._hoistExport(declar, assign, 3));
return;
} else {
// 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)
//
assign = util.template("common-export-default-assign", true);
assign._blockHoist = 0;
nodes.push(assign);
}
}
DefaultFormatter.prototype.exportDeclaration.apply(this, arguments);
};
CommonJSFormatter.prototype.exportSpecifier = function (specifier, node, nodes) {

View File

@@ -1,24 +1,28 @@
module.exports = SystemFormatter;
var DefaultFormatter = require("./_default");
var AMDFormatter = require("./amd");
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
var AMDFormatter = require("./amd");
var useStrict = require("../transformers/use-strict");
var traverse = require("../../traverse");
var util = require("../../util");
var t = require("../../types");
var _ = require("lodash");
function SystemFormatter(file) {
AMDFormatter.apply(this, arguments);
this.moduleNameLiteral = t.literal(this.getModuleName());
this.exportIdentifier = file.generateUidIdentifier("export");
this.noInteropRequire = true;
AMDFormatter.apply(this, arguments);
}
util.inherits(SystemFormatter, AMDFormatter);
SystemFormatter.prototype.getModuleName = DefaultFormatter.prototype.getModuleName;
SystemFormatter.prototype._addImportSource = function (node, exportNode) {
node._importSource = exportNode.source && exportNode.source.value;
return node;
};
SystemFormatter.prototype._exportsWildcard = function (objectIdentifier) {
var leftIdentifier = t.identifier("i");
SystemFormatter.prototype._exportsWildcard = function (objectIdentifier, node) {
var leftIdentifier = this.file.generateUidIdentifier("key");
var valIdentifier = t.memberExpression(objectIdentifier, leftIdentifier, true);
var left = t.variableDeclaration("var", [
@@ -28,14 +32,15 @@ SystemFormatter.prototype._exportsWildcard = function (objectIdentifier) {
var right = objectIdentifier;
var block = t.blockStatement([
this.buildExportCall(leftIdentifier, valIdentifier)
t.expressionStatement(this.buildExportCall(leftIdentifier, valIdentifier))
]);
return t.forInStatement(left, right, block);
return this._addImportSource(t.forInStatement(left, right, block), node);
};
SystemFormatter.prototype._exportsAssign = function (id, init) {
return this.buildExportCall(t.literal(id.name), init, true);
SystemFormatter.prototype._exportsAssign = function (id, init, node) {
var call = this.buildExportCall(t.literal(id.name), init, true);
return this._addImportSource(call, node);
};
SystemFormatter.prototype.remapExportAssignment = function (node) {
@@ -51,32 +56,123 @@ SystemFormatter.prototype.buildExportCall = function (id, init, isStatement) {
}
};
SystemFormatter.prototype.buildRunnerSetters = function () {
return t.arrayExpression(_.map(this.ids, function (uid) {
var moduleIdentifier = t.identifier("m");
SystemFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
AMDFormatter.prototype.importSpecifier.apply(this, arguments);
this._addImportSource(_.last(nodes), node);
};
return t.functionExpression(null, [moduleIdentifier], t.blockStatement([
t.assignmentExpression("=", uid, moduleIdentifier)
]));
SystemFormatter.prototype.buildRunnerSetters = function (block, hoistDeclarators) {
return t.arrayExpression(_.map(this.ids, function (uid, source) {
var nodes = [];
traverse(block, {
enter: function (node) {
if (node._importSource === source) {
if (t.isVariableDeclaration(node)) {
_.each(node.declarations, function (declar) {
hoistDeclarators.push(t.variableDeclarator(declar.id));
nodes.push(t.expressionStatement(
t.assignmentExpression("=", declar.id, declar.init)
));
});
} else {
nodes.push(node);
}
this.remove();
}
}
});
return t.functionExpression(null, [uid], t.blockStatement(nodes));
}));
};
SystemFormatter.prototype.transform = function (ast) {
var program = ast.program;
var hoistDeclarators = [];
var moduleName = this.getModuleName();
var moduleNameLiteral = t.literal(moduleName);
var block = t.blockStatement(program.body);
var runner = util.template("system", {
MODULE_NAME: this.moduleNameLiteral,
MODULE_NAME: moduleNameLiteral,
MODULE_DEPENDENCIES: t.arrayExpression(this.buildDependencyLiterals()),
EXPORT_IDENTIFIER: this.exportIdentifier,
SETTERS: this.buildRunnerSetters(),
EXECUTE: t.functionExpression(null, [], t.blockStatement(program.body))
SETTERS: this.buildRunnerSetters(block, hoistDeclarators),
EXECUTE: t.functionExpression(null, [], block)
}, true);
if (!_.isEmpty(this.ids)) {
var handlerBody = runner.expression.arguments[2].body.body;
handlerBody.unshift(t.variableDeclaration("var", _.map(this.ids, function (uid) {
return t.variableDeclarator(uid);
})));
var handlerBody = runner.expression.arguments[2].body.body;
if (!moduleName) runner.expression.arguments.shift();
var returnStatement = handlerBody.pop();
// hoist up all variable declarations
traverse(block, {
enter: function (node, parent, scope) {
if (t.isFunction(node)) {
// nothing inside is accessible
return this.skip();
}
if (t.isVariableDeclaration(node)) {
if (node.kind !== "var" && !t.isProgram(parent)) { // let, const
// can't be accessed
return;
}
var nodes = [];
_.each(node.declarations, function (declar) {
hoistDeclarators.push(t.variableDeclarator(declar.id));
if (declar.init) {
// no initializer so we can just hoist it as-is
var assign = t.expressionStatement(t.assignmentExpression("=", declar.id, declar.init));
nodes.push(assign);
}
});
// for (var i in test)
// for (var i = 0;;)
if (t.isFor(parent)) {
if (parent.left === node) {
return node.declarations[0].id;
}
if (parent.init === node) {
return t.toSequenceExpression(nodes, scope);
}
}
return nodes;
}
}
});
if (hoistDeclarators.length) {
var hoistDeclar = t.variableDeclaration("var", hoistDeclarators);
hoistDeclar._blockHoist = true;
handlerBody.unshift(hoistDeclar);
}
// hoist up function declarations for circular references
traverse(block, {
enter: function (node) {
if (t.isFunction(node)) this.skip();
if (t.isFunctionDeclaration(node) || node._blockHoist) {
handlerBody.push(node);
this.remove();
}
}
});
handlerBody.push(returnStatement);
if (useStrict._has(block)) {
handlerBody.unshift(block.body.shift());
}
program.body = [runner];

View File

@@ -0,0 +1,37 @@
(function (fn) {
return function () {
var gen = fn.apply(this, arguments);
return new Promise(function (resolve, reject) {
function step(getNext) {
var next;
try {
next = getNext();
} catch(e) {
reject(e);
return;
}
if (next.done) {
resolve(next.value);
return;
}
Promise.resolve(next.value).then(function (v) {
step(function () {
return gen.next(v);
});
}, function (e) {
step(function () {
return gen["throw"](e);
});
});
}
step(function () {
return gen.next();
});
});
}
})

View File

@@ -0,0 +1 @@
Function.prototype.bind

View File

@@ -1,3 +1,3 @@
if (SUPER_NAME) {
if (SUPER_NAME !== null) {
SUPER_NAME.apply(this, arguments);
}

View File

@@ -0,0 +1 @@
module.exports = Object.assign(exports["default"], exports);

View File

@@ -0,0 +1 @@
CORE_ID.$for.getIterator(VALUE);

View File

@@ -0,0 +1 @@
var VARIABLE_NAME = ARGUMENTS[ARGUMENT_KEY] === undefined ? DEFAULT_VALUE : ARGUMENTS[ARGUMENT_KEY];

View File

@@ -0,0 +1,8 @@
(function (obj, defaults) {
for (var key in defaults) {
if (obj[key] === undefined) {
obj[key] = defaults[key];
}
}
return obj;
})

View File

@@ -0,0 +1,8 @@
(function (obj, key, value) {
return Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
});

View File

@@ -0,0 +1,7 @@
(function (obj) {
for (var i in obj) {
if (exports[i] !== undefined) {
exports[i] = obj[i];
}
}
})

View File

@@ -1,4 +1,7 @@
(function (child, parent) {
if (typeof parent !== "function" && parent !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof parent);
}
child.prototype = Object.create(parent && parent.prototype, {
constructor: {
value: child,

View File

@@ -0,0 +1,3 @@
(function (obj) {
return obj && obj.constructor === Object ? obj : { default: obj };
})

View File

@@ -0,0 +1,11 @@
(function (FUNCTION_KEY) {
var WRAPPER_KEY = function FUNCTION_ID() {
return FUNCTION_KEY.apply(this, arguments);
};
WRAPPER_KEY.toString = function () {
return FUNCTION_KEY.toString();
};
return WRAPPER_KEY;
})(FUNCTION)

View File

@@ -0,0 +1,3 @@
for (var KEY = START; KEY < ARGUMENTS.length; KEY++) {
ARRAY[KEY] = ARGUMENTS[KEY];
}

View File

@@ -0,0 +1,12 @@
(function (arr, i) {
if (Array.isArray(arr)) {
return arr;
} else {
var _arr = [];
for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) {
_arr.push(_step.value);
if (i && _arr.length === i) break;
}
return _arr;
}
});

Some files were not shown because too many files have changed in this diff Show More