From bcec0eef86bca21fafbb8f526e2ba45b8849eab5 Mon Sep 17 00:00:00 2001 From: Marek Suscak Date: Tue, 6 Dec 2016 13:17:28 +0100 Subject: [PATCH 01/10] Move Blog link to the menu on the left. --- _data/navigation.yml | 2 ++ _includes/header.html | 3 --- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/_data/navigation.yml b/_data/navigation.yml index a065a415cc..a53d5909e8 100644 --- a/_data/navigation.yml +++ b/_data/navigation.yml @@ -27,3 +27,5 @@ url: /repl/ - title: FAQ url: /docs/faq +- title: Blog + url: /blog/ diff --git a/_includes/header.html b/_includes/header.html index 391bbeeb1b..9773702a74 100644 --- a/_includes/header.html +++ b/_includes/header.html @@ -44,9 +44,6 @@
  • Slack
  • -
  • - Blog -
  • Twitter
  • From 1baca25bc9841578035c90be6cf38af681c5ad79 Mon Sep 17 00:00:00 2001 From: Marek Suscak Date: Tue, 6 Dec 2016 14:54:50 +0100 Subject: [PATCH 02/10] Reorganize the sections. --- _data/navigation.yml | 36 +- docs/editors.md | 6 + docs/setup.md | 2 + docs/usage/api.md | 50 ++ docs/usage/babelrc.md | 4 +- docs/usage/browser.md | 29 -- docs/usage/cli.md | 2 +- docs/usage/options.md | 52 -- docs/learn-es6.md => learn-es6.md | 0 learn-js.md | 819 ++++++++++++++++++++++++++++++ 10 files changed, 897 insertions(+), 103 deletions(-) create mode 100644 docs/editors.md delete mode 100644 docs/usage/browser.md delete mode 100644 docs/usage/options.md rename docs/learn-es6.md => learn-es6.md (100%) create mode 100644 learn-js.md diff --git a/_data/navigation.yml b/_data/navigation.yml index a53d5909e8..cd737219af 100644 --- a/_data/navigation.yml +++ b/_data/navigation.yml @@ -1,31 +1,29 @@ - title: Learn ES2015 - url: /docs/learn-es2015/ -- title: Setup - url: /docs/setup/ -- title: Plugins - url: /docs/plugins/ -- title: Usage - url: /docs/usage/ + url: /learn-js/ +- title: Docs + url: /docs subnav: - - title: Options - url: /docs/usage/options/ + - title: Setup + url: /docs/setup/ + - title: Plugins + url: /docs/plugins/ + - title: Polyfill + url: /docs/usage/polyfill/ - title: Caveats url: /docs/usage/caveats/ - - title: babelrc - url: /docs/usage/babelrc/ + - title: Editors + url: /docs/editors + - title: API + url: /docs/usage/api/ - title: CLI url: /docs/usage/cli/ - - title: Polyfill - url: /docs/usage/polyfill/ - title: babel-register url: /docs/usage/babel-register/ - - title: API - url: /docs/usage/api/ - - title: Browser - url: /docs/usage/browser/ + - title: .babelrc + url: /docs/usage/babelrc/ - title: Try it out url: /repl/ -- title: FAQ - url: /docs/faq - title: Blog url: /blog/ +- title: FAQ + url: /docs/faq diff --git a/docs/editors.md b/docs/editors.md new file mode 100644 index 0000000000..ac5ebfa199 --- /dev/null +++ b/docs/editors.md @@ -0,0 +1,6 @@ +--- +layout: docs +title: Editors +description: How to +permalink: /docs/editors +--- diff --git a/docs/setup.md b/docs/setup.md index 404d5eb7a8..5284f6f26e 100644 --- a/docs/setup.md +++ b/docs/setup.md @@ -7,6 +7,8 @@ redirect_from: - /docs/using-babel/ - /plugins.html - /docs/using-6to5/ + - /docs/usage/browser/ + - browser.html custom_js_with_timestamps: - tools.js --- diff --git a/docs/usage/api.md b/docs/usage/api.md index dc95e9150d..cd64877174 100644 --- a/docs/usage/api.md +++ b/docs/usage/api.md @@ -4,6 +4,8 @@ title: API description: How to use the Node.js API. permalink: /docs/usage/api/ package: babel-core +redirect_from: +- /docs/usage/options/ --- ```javascript @@ -70,3 +72,51 @@ const code = "if (true) return;"; const ast = babylon.parse(code, { allowReturnOutsideFunction: true }); const { code, map, ast } = babel.transformFromAst(ast, code, options); ``` + +## Options + +
    +

    Babel CLI

    +

    + You can pass these options from the Babel CLI like so: +

    +

    + babel --name=value +

    +
    + +Following is a table of the options you can use: + +| Option | Default | Description | +| ------------------------ | -------------------- | ------------------------------- | +| `filename` | `"unknown"` | Filename for use in errors etc. | +| `filenameRelative` | `(filename)` | Filename relative to `sourceRoot`. | +| `presets` | `[]` | List of [presets](/docs/plugins/#presets) (a set of plugins) to load and use. | +| `plugins` | `[]` | List of [plugins](/docs/plugins/) to load and use. | +| `parserOpts` | `{}` | An object containing the options to be passed down to the babel parser, babylon | +| `generatorOpts` | `{}` | An object containing the options to be passed down to the babel code generator, babel-generator | +| `highlightCode` | `true` | ANSI highlight syntax error code frames | +| `only` | `null` | A [glob](https://github.com/isaacs/minimatch), regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile a non-matching file it's returned verbatim. | +| `ignore` | `null` | Opposite to the `only` option. `ignore` is disregarded if `only` is specified. | +| `auxiliaryCommentBefore` | `null` | Attach a comment before all non-user injected code. | +| `auxiliaryCommentAfter` | `null` | Attach a comment after all non-user injected code. | +| `sourceMaps` | `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. If set to `"both"` then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!** To have sourcemaps emitted using the CLI, you must pass it the `--source-maps` option. | +| `inputSourceMap` | `null` | A source map object that the output source map will be based on. | +| `sourceMapTarget` | `(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. | +| `moduleIds` | `false` | If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules) | +| `moduleId` | `null` | Specify a custom name for module ids. | +| `getModuleId` | `null` | Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. If falsy value is returned then the generated module id is used. | +| `resolveModuleSource` | `null` | Resolve a module source ie. `import "SOURCE";` to a custom value. Called as `resolveModuleSource(source, filename)`. | +| `code` | `true` | Enable code generation | +| `no-babelrc` | [CLI flag](http://babeljs.io/docs/usage/cli/#ignoring-babelrc) | Specify whether or not to use .babelrc and .babelignore files. Only available when using the CLI. | +| `ast` | `true` | Include the AST in the returned object | +| `compact` | `"auto"` | Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >100KB. | +| `minified` | `false` | Should the output be minified (not printing last semicolons in blocks, printing literal string values instead of escaped ones, stripping `()` from `new` when safe) | +| `comments` | `true` | Output comments in generated output. | +| `shouldPrintComment` | `null` | An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE:** This overrides the `comment` option when used. | +| `env` | `{}` | This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { /* specific options */ } } }` which will use those options when the enviroment variable `BABEL_ENV` is set to `"production"`. If `BABEL_ENV` isn't set then `NODE_ENV` will be used, if it's not set then it defaults to `"development"` | +| `retainLines` | `false` | Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (**NOTE:** This will not retain the columns) | +| `extends` | `null` | A path to an `.babelrc` file to extend | diff --git a/docs/usage/babelrc.md b/docs/usage/babelrc.md index f0d74c2f1c..b16eaee86e 100644 --- a/docs/usage/babelrc.md +++ b/docs/usage/babelrc.md @@ -1,7 +1,7 @@ --- layout: docs -title: babelrc -description: How to use the babelrc +title: .babelrc +description: How to use the .babelrc permalink: /docs/usage/babelrc/ --- diff --git a/docs/usage/browser.md b/docs/usage/browser.md deleted file mode 100644 index d1f774d48f..0000000000 --- a/docs/usage/browser.md +++ /dev/null @@ -1,29 +0,0 @@ ---- -layout: docs -title: Browser -description: How to compile in the browser. -permalink: /docs/usage/browser/ -redirect_from: /browser.html ---- - -
    -

    - -

    -

    - 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 setup build systems - for more information. -

    -
    - -## `babel-browser` has been removed. - -Use a bundler like [browserify](https://babeljs.io/docs/setup/#browserify)/[webpack](https://babeljs.io/docs/setup/#webpack) or just `require('babel-core')`. - -## [babel-standalone](https://github.com/Daniel15/babel-standalone) - -If you don't want to do it yourself, you can also use [babel-standalone](https://github.com/Daniel15/babel-standalone) which is a pre-built babel with all of the presets and is used in the [Babel REPL](https://babeljs.io/repl). - - diff --git a/docs/usage/cli.md b/docs/usage/cli.md index 63896ae6c2..4351feec15 100644 --- a/docs/usage/cli.md +++ b/docs/usage/cli.md @@ -118,7 +118,7 @@ babel --no-babelrc script.js --out-file script-compiled.js --presets=add-module- ### Advanced Usage -There are many more options available in the babel CLI, see [options](/docs/usage/options/), `babel --help` and other sections for more information. +There are many more options available in the babel CLI, see [options](/docs/usage/api/#options), `babel --help` and other sections for more information. ## babel-node diff --git a/docs/usage/options.md b/docs/usage/options.md deleted file mode 100644 index f2642ce537..0000000000 --- a/docs/usage/options.md +++ /dev/null @@ -1,52 +0,0 @@ ---- -layout: docs -title: Options -description: Options for babel transpiling. -permalink: /docs/usage/options/ ---- - -## Usage - -```js -babel.transform(code, options); -``` - -```sh -babel --name=value -``` - -## Options - -| Option | Default | Description | -| ------------------------ | -------------------- | ------------------------------- | -| `filename` | `"unknown"` | Filename for use in errors etc. | -| `filenameRelative` | `(filename)` | Filename relative to `sourceRoot`. | -| `presets` | `[]` | List of [presets](/docs/plugins/#presets) (a set of plugins) to load and use. | -| `plugins` | `[]` | List of [plugins](/docs/plugins/) to load and use. | -| `parserOpts` | `{}` | An object containing the options to be passed down to the babel parser, babylon | -| `generatorOpts` | `{}` | An object containing the options to be passed down to the babel code generator, babel-generator | -| `highlightCode` | `true` | ANSI highlight syntax error code frames | -| `only` | `null` | A [glob](https://github.com/isaacs/minimatch), regex, or mixed array of both, matching paths to **only** compile. Can also be an array of arrays containing paths to explicitly match. When attempting to compile a non-matching file it's returned verbatim. | -| `ignore` | `null` | Opposite to the `only` option. `ignore` is disregarded if `only` is specified. | -| `auxiliaryCommentBefore` | `null` | Attach a comment before all non-user injected code. | -| `auxiliaryCommentAfter` | `null` | Attach a comment after all non-user injected code. | -| `sourceMaps` | `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. If set to `"both"` then a `map` property is returned as well as a source map comment appended. **This does not emit sourcemap files by itself!** To have sourcemaps emitted using the CLI, you must pass it the `--source-maps` option. | -| `inputSourceMap` | `null` | A source map object that the output source map will be based on. | -| `sourceMapTarget` | `(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. | -| `moduleIds` | `false` | If truthy, insert an explicit id for modules. By default, all modules are anonymous. (Not available for `common` modules) | -| `moduleId` | `null` | Specify a custom name for module ids. | -| `getModuleId` | `null` | Specify a custom callback to generate a module id with. Called as `getModuleId(moduleName)`. If falsy value is returned then the generated module id is used. | -| `resolveModuleSource` | `null` | Resolve a module source ie. `import "SOURCE";` to a custom value. Called as `resolveModuleSource(source, filename)`. | -| `code` | `true` | Enable code generation | -| `no-babelrc` | [CLI flag](http://babeljs.io/docs/usage/cli/#ignoring-babelrc) | Specify whether or not to use .babelrc and .babelignore files. Only available when using the CLI. | -| `ast` | `true` | Include the AST in the returned object | -| `compact` | `"auto"` | Do not include superfluous whitespace characters and line terminators. When set to `"auto"` compact is set to `true` on input sizes of >100KB. | -| `minified` | `false` | Should the output be minified (not printing last semicolons in blocks, printing literal string values instead of escaped ones, stripping `()` from `new` when safe) | -| `comments` | `true` | Output comments in generated output. | -| `shouldPrintComment` | `null` | An optional callback that controls whether a comment should be output or not. Called as `shouldPrintComment(commentContents)`. **NOTE:** This overrides the `comment` option when used. | -| `env` | `{}` | This is an object of keys that represent different environments. For example, you may have: `{ env: { production: { /* specific options */ } } }` which will use those options when the enviroment variable `BABEL_ENV` is set to `"production"`. If `BABEL_ENV` isn't set then `NODE_ENV` will be used, if it's not set then it defaults to `"development"` | -| `retainLines` | `false` | Retain line numbers. This will lead to wacky code but is handy for scenarios where you can't use source maps. (**NOTE:** This will not retain the columns) | -| `extends` | `null` | A path to an `.babelrc` file to extend | diff --git a/docs/learn-es6.md b/learn-es6.md similarity index 100% rename from docs/learn-es6.md rename to learn-es6.md diff --git a/learn-js.md b/learn-js.md new file mode 100644 index 0000000000..364b69516e --- /dev/null +++ b/learn-js.md @@ -0,0 +1,819 @@ +--- +layout: docs +title: Learn ES2015 +description: A detailed overview of ECMAScript 2015 features. Based on Luke Hoban's es6features repo. +permalink: /learn-js/ +redirect_from: + - /docs/learn-es6/ + - /docs/learn-es2015/ + - /features.html + - /docs/tour/ +--- + +
    +

    es6features

    +

    + This document was originally taken from Luke Hoban's excellent + es6features repo. Go give it a star + on GitHub! +

    +
    + +
    +

    REPL

    +

    + Be sure to try these features out in the online + REPL. +

    +
    + +## Introduction + +> ECMAScript 2015 is an ECMAScript standard that was ratified in June 2015. + +ES2015 is a significant update to the language, and the first major update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is [underway now](https://kangax.github.io/es5-compat-table/es6/). + +See the [ES2015 standard](http://www.ecma-international.org/ecma-262/6.0/index.html) +for full specification of the ECMAScript 2015 language. + +## ECMAScript 2015 Features + + + + +### Arrows and Lexical This + +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. If an arrow is inside another function, +it shares the "arguments" variable of its parent function. + +```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)); + } +}; + +// Lexical arguments +function square() { + let example = () => { + let numbers = []; + for (let number of arguments) { + numbers.push(number * number); + } + + return numbers; + }; + + return example(); +} + +square(2, 4, 7.5, 8, 11.5, 21); // returns: [4, 16, 56.25, 64, 132.25, 441] +``` + +### Classes + +ES2015 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 = { + // Sets the prototype. "__proto__" or '__proto__' would also work. + __proto__: theProtoObj, + // Computed property name does not set prototype or trigger early error for + // duplicate __proto__ properties. + ['__proto__']: somethingElse, + // Shorthand for ‘handler: handler’ + handler, + // Methods + toString() { + // Super calls + return "d " + super.toString(); + }, + // Computed (dynamic) property names + [ "prop_" + (() => 42)() ]: 42 +}; +``` + +
    +

    + The __proto__ property requires native support, and was deprecated in previous ECMAScript versions. Most engines now support the property, but some do not. Also, note that only web browsers are required to implement it, as it's in Annex B. It is available in Node. +

    +
    + +### 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 +`This is a pretty little template string.` + +// Multiline strings +`In ES5 this is + not legal.` + +// Interpolate variable bindings +var name = "Bob", time = "today"; +`Hello ${name}, how are you ${time}?` + +// Unescaped template strings +String.raw`In ES5 "\n" is a line-feed.` + +// 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]; +a === 1; +b === 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; + +// Destructuring + defaults arguments +function r({x, y, w = 10, h = 10}) { + return x + y + w + h; +} +r({x:1, y:2}) === 23 +``` + +### 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; + { + // this is ok since it's a block scoped name + const x = "sneaky"; + // error, was just defined with `const` above + x = "foo"; + } + // this is ok since it was declared with `let` + x = "bar"; + // error, already declared above in this block + let x = "inner"; + } +} +``` + +### Iterators + For..Of + +Iterator objects enable custom iteration like CLR IEnumerable or Java +Iterable. Generalize `for..in` to custom iterator-based iteration with +`for..of`. Don’t require realizing an array, enabling lazy design patterns like +LINQ. + +```js +let fibonacci = { + [Symbol.iterator]() { + let pre = 0, cur = 1; + return { + next() { + [pre, cur] = [cur, pre + cur]; + return { done: false, value: cur } + } + } + } +} + +for (var n of fibonacci) { + // truncate the sequence at 1000 + if (n > 1000) + break; + console.log(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 +} +``` + +
    +

    Support via polyfill

    +

    + In order to use Iterators you must include the Babel polyfill. +

    +
    + +### 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](https://github.com/lukehoban/ecmascript-asyncawait). + +```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; + console.log(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); +} +``` + +
    +

    Support via polyfill

    +

    + In order to use Generators you must include the Babel polyfill. +

    +
    + +### Comprehensions + +Removed in Babel 6.0 + +### 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 +import * as math from "lib/math"; +console.log("2π = " + math.sum(math.pi, math.pi)); +``` +```js +// otherApp.js +import {sum, pi} from "lib/math"; +console.log("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 +import exp, {pi, e} from "lib/mathplusplus"; +console.log("e^π = " + exp(pi)); +``` + +
    +

    Module Formatters

    +

    + Babel can transpile ES2015 Modules to several different formats including + Common.js, AMD, System, and UMD. You can even create your own. For more + details see the modules docs. +

    +
    + +### Module Loaders + +
    +

    Not part of ES2015

    +

    + This is left as implementation-defined within the ECMAScript 2015 specification. The eventual standard will be in WHATWG's Loader specification, but that is currently a work in progress. What is below is from a previous ES2015 draft. +

    +
    + +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 +``` + +
    +

    Additional polyfill needed

    +

    + Since Babel defaults to using common.js modules, it does not include the + polyfill for the module loader API. Get it + here. +

    +
    + +
    +

    Using Module Loader

    +

    + In order to use this, you'll need to tell Babel to use the + system module formatter. Also be sure to check out + System.js +

    +
    + + +### Map + Set + WeakMap + WeakSet + +Efficient data structures for common algorithms. WeakMaps provides leak-free +object-key’d side tables. + +```js +// Sets +var s = new Set(); +s.add("hello").add("goodbye").add("hello"); +s.size === 2; +s.has("hello") === true; + +// Maps +var m = new Map(); +m.set("hello", 42); +m.set(s, 34); +m.get(s) == 34; + +// Weak Maps +var wm = new WeakMap(); +wm.set(s, { extra: 42 }); +wm.size === undefined + +// Weak Sets +var ws = new WeakSet(); +ws.add({ data: 42 }); +// Because the added object has no other references, it will not be held in the set +``` + +
    +

    Support via polyfill

    +

    + In order to support Maps, Sets, WeakMaps, and WeakSets in all environments you must include the Babel polyfill. +

    +
    + +### 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 = +{ + // target.prop + get: ..., + // target.prop = value + set: ..., + // 'prop' in target + has: ..., + // delete target.prop + deleteProperty: ..., + // target(...args) + apply: ..., + // new target(...args) + construct: ..., + // Object.getOwnPropertyDescriptor(target, 'prop') + getOwnPropertyDescriptor: ..., + // Object.defineProperty(target, 'prop', descriptor) + defineProperty: ..., + // Object.getPrototypeOf(target), Reflect.getPrototypeOf(target), + // target.__proto__, object.isPrototypeOf(target), object instanceof target + getPrototypeOf: ..., + // Object.setPrototypeOf(target), Reflect.setPrototypeOf(target) + setPrototypeOf: ..., + // for (let i in target) {} + enumerate: ..., + // Object.keys(target) + ownKeys: ..., + // Object.preventExtensions(target) + preventExtensions: ..., + // Object.isExtensible(target) + isExtensible :... +} +``` + +
    +

    Unsupported feature

    +

    + Due to the limitations of ES5, Proxies cannot be transpiled or polyfilled. See support in various JavaScript engines. +

    +
    + +### 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] ... + } + }; + + // Limited support from Babel, full support requires native implementation. + typeof key === "symbol" +})(); + +var c = new MyClass("hello") +c["key"] === undefined +``` + +
    +

    Limited support via polyfill

    +

    + Limited support requires the Babel polyfill. Due to language limitations, some features can't be transpiled or polyfilled. See core.js's caveats section for more details. +

    +
    + +### Subclassable Built-ins + +In ES2015, built-ins like `Array`, `Date` and DOM `Element`s can be subclassed. + +```js +// User code of Array subclass +class MyArray extends Array { + constructor(...args) { super(...args); } +} + +var arr = new MyArray(); +arr[1] = 12; +arr.length == 2 +``` + +
    +

    Partial support

    +

    + Built-in subclassability should be evaluated on a case-by-case basis as classes such as HTMLElement can be subclassed while many such as Date, Array and Error cannot be due to ES5 engine limitations. +

    +
    + +### 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".includes("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) }) +``` + +
    +

    Limited support from polyfill

    +

    + Most of these APIs are supported by the Babel polyfill. However, certain + features are omitted for various reasons (e.g. + String.prototype.normalize needs a lot of additional code to + support). You can find more polyfills + here. +

    +
    + +### Binary and Octal Literals +Two new numeric literal forms are added for binary (`b`) and octal (`o`). + +```js +0b111110111 === 503 // true +0o767 === 503 // true +``` + +
    +

    Only supports literal form

    +

    + Babel is only able to transform 0o767 and not + Number("0o767"). +

    +
    + + +### 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)]); +}) +``` + +
    +

    Support via polyfill

    +

    + In order to support Promises you must include the Babel polyfill. +

    +
    + +### 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 +var O = {a: 1}; +Object.defineProperty(O, 'b', {value: 2}); +O[Symbol('c')] = 3; + +Reflect.ownKeys(O); // ['a', 'b', Symbol(c)] + +function C(a, b){ + this.c = a + b; +} +var instance = Reflect.construct(C, [20, 22]); +instance.c; // 42 +``` + +
    +

    Support via polyfill

    +

    + In order to use the Reflect API you must include the Babel polyfill. +

    +
    + +### 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 ES2015 +factorial(100000) +``` + +
    +

    Temporarily Removed in Babel 6

    +

    + Only explicit self referencing tail recursion was supported due to the + complexity and performance impact of supporting tail calls globally. + Removed due to other bugs and will be re-implemented. +

    +
    From 5636f8ae2d024afa7e69ca9cbeaf5589779bb780 Mon Sep 17 00:00:00 2001 From: Marek Suscak Date: Tue, 6 Dec 2016 14:58:07 +0100 Subject: [PATCH 03/10] Remove the old learn-es6. --- learn-es6.md | 818 --------------------------------------------------- 1 file changed, 818 deletions(-) delete mode 100644 learn-es6.md diff --git a/learn-es6.md b/learn-es6.md deleted file mode 100644 index 8ce4c4c1c0..0000000000 --- a/learn-es6.md +++ /dev/null @@ -1,818 +0,0 @@ ---- -layout: docs -title: Learn ES2015 -description: A detailed overview of ECMAScript 2015 features. Based on Luke Hoban's es6features repo. -permalink: /docs/learn-es2015/ -redirect_from: - - /docs/learn-es6/ - - /features.html - - /docs/tour/ ---- - -
    -

    es6features

    -

    - This document was originally taken from Luke Hoban's excellent - es6features repo. Go give it a star - on GitHub! -

    -
    - -
    -

    REPL

    -

    - Be sure to try these features out in the online - REPL. -

    -
    - -## Introduction - -> ECMAScript 2015 is an ECMAScript standard that was ratified in June 2015. - -ES2015 is a significant update to the language, and the first major update to the language since ES5 was standardized in 2009. Implementation of these features in major JavaScript engines is [underway now](https://kangax.github.io/es5-compat-table/es6/). - -See the [ES2015 standard](http://www.ecma-international.org/ecma-262/6.0/index.html) -for full specification of the ECMAScript 2015 language. - -## ECMAScript 2015 Features - - - - -### Arrows and Lexical This - -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. If an arrow is inside another function, -it shares the "arguments" variable of its parent function. - -```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)); - } -}; - -// Lexical arguments -function square() { - let example = () => { - let numbers = []; - for (let number of arguments) { - numbers.push(number * number); - } - - return numbers; - }; - - return example(); -} - -square(2, 4, 7.5, 8, 11.5, 21); // returns: [4, 16, 56.25, 64, 132.25, 441] -``` - -### Classes - -ES2015 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 = { - // Sets the prototype. "__proto__" or '__proto__' would also work. - __proto__: theProtoObj, - // Computed property name does not set prototype or trigger early error for - // duplicate __proto__ properties. - ['__proto__']: somethingElse, - // Shorthand for ‘handler: handler’ - handler, - // Methods - toString() { - // Super calls - return "d " + super.toString(); - }, - // Computed (dynamic) property names - [ "prop_" + (() => 42)() ]: 42 -}; -``` - -
    -

    - The __proto__ property requires native support, and was deprecated in previous ECMAScript versions. Most engines now support the property, but some do not. Also, note that only web browsers are required to implement it, as it's in Annex B. It is available in Node. -

    -
    - -### 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 -`This is a pretty little template string.` - -// Multiline strings -`In ES5 this is - not legal.` - -// Interpolate variable bindings -var name = "Bob", time = "today"; -`Hello ${name}, how are you ${time}?` - -// Unescaped template strings -String.raw`In ES5 "\n" is a line-feed.` - -// 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]; -a === 1; -b === 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; - -// Destructuring + defaults arguments -function r({x, y, w = 10, h = 10}) { - return x + y + w + h; -} -r({x:1, y:2}) === 23 -``` - -### 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; - { - // this is ok since it's a block scoped name - const x = "sneaky"; - // error, was just defined with `const` above - x = "foo"; - } - // this is ok since it was declared with `let` - x = "bar"; - // error, already declared above in this block - let x = "inner"; - } -} -``` - -### Iterators + For..Of - -Iterator objects enable custom iteration like CLR IEnumerable or Java -Iterable. Generalize `for..in` to custom iterator-based iteration with -`for..of`. Don’t require realizing an array, enabling lazy design patterns like -LINQ. - -```js -let fibonacci = { - [Symbol.iterator]() { - let pre = 0, cur = 1; - return { - next() { - [pre, cur] = [cur, pre + cur]; - return { done: false, value: cur } - } - } - } -} - -for (var n of fibonacci) { - // truncate the sequence at 1000 - if (n > 1000) - break; - console.log(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 -} -``` - -
    -

    Support via polyfill

    -

    - In order to use Iterators you must include the Babel polyfill. -

    -
    - -### 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](https://github.com/lukehoban/ecmascript-asyncawait). - -```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; - console.log(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); -} -``` - -
    -

    Support via polyfill

    -

    - In order to use Generators you must include the Babel polyfill. -

    -
    - -### Comprehensions - -Removed in Babel 6.0 - -### 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 -import * as math from "lib/math"; -console.log("2π = " + math.sum(math.pi, math.pi)); -``` -```js -// otherApp.js -import {sum, pi} from "lib/math"; -console.log("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 -import exp, {pi, e} from "lib/mathplusplus"; -console.log("e^π = " + exp(pi)); -``` - -
    -

    Module Formatters

    -

    - Babel can transpile ES2015 Modules to several different formats including - Common.js, AMD, System, and UMD. You can even create your own. For more - details see the modules docs. -

    -
    - -### Module Loaders - -
    -

    Not part of ES2015

    -

    - This is left as implementation-defined within the ECMAScript 2015 specification. The eventual standard will be in WHATWG's Loader specification, but that is currently a work in progress. What is below is from a previous ES2015 draft. -

    -
    - -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 -``` - -
    -

    Additional polyfill needed

    -

    - Since Babel defaults to using common.js modules, it does not include the - polyfill for the module loader API. Get it - here. -

    -
    - -
    -

    Using Module Loader

    -

    - In order to use this, you'll need to tell Babel to use the - system module formatter. Also be sure to check out - System.js -

    -
    - - -### Map + Set + WeakMap + WeakSet - -Efficient data structures for common algorithms. WeakMaps provides leak-free -object-key’d side tables. - -```js -// Sets -var s = new Set(); -s.add("hello").add("goodbye").add("hello"); -s.size === 2; -s.has("hello") === true; - -// Maps -var m = new Map(); -m.set("hello", 42); -m.set(s, 34); -m.get(s) == 34; - -// Weak Maps -var wm = new WeakMap(); -wm.set(s, { extra: 42 }); -wm.size === undefined - -// Weak Sets -var ws = new WeakSet(); -ws.add({ data: 42 }); -// Because the added object has no other references, it will not be held in the set -``` - -
    -

    Support via polyfill

    -

    - In order to support Maps, Sets, WeakMaps, and WeakSets in all environments you must include the Babel polyfill. -

    -
    - -### 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 = -{ - // target.prop - get: ..., - // target.prop = value - set: ..., - // 'prop' in target - has: ..., - // delete target.prop - deleteProperty: ..., - // target(...args) - apply: ..., - // new target(...args) - construct: ..., - // Object.getOwnPropertyDescriptor(target, 'prop') - getOwnPropertyDescriptor: ..., - // Object.defineProperty(target, 'prop', descriptor) - defineProperty: ..., - // Object.getPrototypeOf(target), Reflect.getPrototypeOf(target), - // target.__proto__, object.isPrototypeOf(target), object instanceof target - getPrototypeOf: ..., - // Object.setPrototypeOf(target), Reflect.setPrototypeOf(target) - setPrototypeOf: ..., - // for (let i in target) {} - enumerate: ..., - // Object.keys(target) - ownKeys: ..., - // Object.preventExtensions(target) - preventExtensions: ..., - // Object.isExtensible(target) - isExtensible :... -} -``` - -
    -

    Unsupported feature

    -

    - Due to the limitations of ES5, Proxies cannot be transpiled or polyfilled. See support in various JavaScript engines. -

    -
    - -### 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] ... - } - }; - - // Limited support from Babel, full support requires native implementation. - typeof key === "symbol" -})(); - -var c = new MyClass("hello") -c["key"] === undefined -``` - -
    -

    Limited support via polyfill

    -

    - Limited support requires the Babel polyfill. Due to language limitations, some features can't be transpiled or polyfilled. See core.js's caveats section for more details. -

    -
    - -### Subclassable Built-ins - -In ES2015, built-ins like `Array`, `Date` and DOM `Element`s can be subclassed. - -```js -// User code of Array subclass -class MyArray extends Array { - constructor(...args) { super(...args); } -} - -var arr = new MyArray(); -arr[1] = 12; -arr.length == 2 -``` - -
    -

    Partial support

    -

    - Built-in subclassability should be evaluated on a case-by-case basis as classes such as HTMLElement can be subclassed while many such as Date, Array and Error cannot be due to ES5 engine limitations. -

    -
    - -### 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".includes("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) }) -``` - -
    -

    Limited support from polyfill

    -

    - Most of these APIs are supported by the Babel polyfill. However, certain - features are omitted for various reasons (e.g. - String.prototype.normalize needs a lot of additional code to - support). You can find more polyfills - here. -

    -
    - -### Binary and Octal Literals -Two new numeric literal forms are added for binary (`b`) and octal (`o`). - -```js -0b111110111 === 503 // true -0o767 === 503 // true -``` - -
    -

    Only supports literal form

    -

    - Babel is only able to transform 0o767 and not - Number("0o767"). -

    -
    - - -### 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)]); -}) -``` - -
    -

    Support via polyfill

    -

    - In order to support Promises you must include the Babel polyfill. -

    -
    - -### 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 -var O = {a: 1}; -Object.defineProperty(O, 'b', {value: 2}); -O[Symbol('c')] = 3; - -Reflect.ownKeys(O); // ['a', 'b', Symbol(c)] - -function C(a, b){ - this.c = a + b; -} -var instance = Reflect.construct(C, [20, 22]); -instance.c; // 42 -``` - -
    -

    Support via polyfill

    -

    - In order to use the Reflect API you must include the Babel polyfill. -

    -
    - -### 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 ES2015 -factorial(100000) -``` - -
    -

    Temporarily Removed in Babel 6

    -

    - Only explicit self referencing tail recursion was supported due to the - complexity and performance impact of supporting tail calls globally. - Removed due to other bugs and will be re-implemented. -

    -
    From 67bb5348dd89ea917dbfcae77540cc7a41cca933 Mon Sep 17 00:00:00 2001 From: Marek Suscak Date: Tue, 6 Dec 2016 15:22:12 +0100 Subject: [PATCH 04/10] Add preliminary content for the Editors page. --- docs/editors.md | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/docs/editors.md b/docs/editors.md index ac5ebfa199..e5803d67ef 100644 --- a/docs/editors.md +++ b/docs/editors.md @@ -1,6 +1,22 @@ --- layout: docs title: Editors -description: How to +description: How to get syntax highlighting to work permalink: /docs/editors --- + +## Atom + +TBD + +## Sublime Text 3 + +TBD + +## Visual Studio Code + +TBD + +## WebStorm + +TBD From 6a35a81131d140194684ccf9dfb93a468c835612 Mon Sep 17 00:00:00 2001 From: Marek Suscak Date: Tue, 6 Dec 2016 15:42:33 +0100 Subject: [PATCH 05/10] Add the contents for Editors page. --- docs/editors.md | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/docs/editors.md b/docs/editors.md index e5803d67ef..8f14f7131d 100644 --- a/docs/editors.md +++ b/docs/editors.md @@ -1,22 +1,38 @@ --- layout: docs title: Editors -description: How to get syntax highlighting to work +description: Learn how to use Babel in the editor of choice permalink: /docs/editors --- -## Atom +## Syntax Highlighting -TBD +Most popular editors these days do support ES2015+ syntax highlighting. +Some of them require installing additional extensions while some others +don't. This guide should help you get the syntax highlighting to work. -## Sublime Text 3 +If you're looking for more advanced integrations, you may want to +take a look at the [Setup](/docs/setup) guide. -TBD +### Atom -## Visual Studio Code +Install [language-babel](https://atom.io/packages/language-babel) package +and follow the [instructions](https://github.com/gandm/language-babel#installation). -TBD +### Sublime Text 3 -## WebStorm +First, [install Package Control](https://packagecontrol.io/installation). +Then install [Babel](https://packagecontrol.io/packages/Babel) package +from the Package Control menu and follow +the [instructions](https://github.com/babel/babel-sublime#installation). -TBD +### Visual Studio Code + +Install [Babel ES6/ES7](https://marketplace.visualstudio.com/items?itemName=dzannotti.vscode-babel-coloring) +extension and follow the instructions. + +### WebStorm + +Seems like WebStorm now ships with support for ES2015+ without requiring you +to install additional extensions. You might need to +[enable it](https://blog.jetbrains.com/webstorm/2015/05/ecmascript-6-in-webstorm-transpiling/) though. From 12e0fd347ab71323ed60dc01f701c3c74696a3bb Mon Sep 17 00:00:00 2001 From: Marek Suscak Date: Tue, 6 Dec 2016 15:43:55 +0100 Subject: [PATCH 06/10] Fix link to the options section. --- docs/usage/api.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/usage/api.md b/docs/usage/api.md index cd64877174..90bed99973 100644 --- a/docs/usage/api.md +++ b/docs/usage/api.md @@ -14,7 +14,7 @@ import { transform } from 'babel-core'; import * as babel from 'babel-core'; ``` -## babel.transform(code: string, [options?](/docs/usage/options): Object) +## babel.transform(code: string, [options?](/docs/usage/api/#options): Object) Transforms the passed in `code`. Returning an object with the generated code, source map, and AST. @@ -32,7 +32,7 @@ result.map; result.ast; ``` -## babel.transformFile(filename: string, [options?](/docs/usage/options): Object, callback: Function) +## babel.transformFile(filename: string, [options?](/docs/usage/api/#options): Object, callback: Function) Asynchronously transforms the entire contents of a file. @@ -48,7 +48,7 @@ babel.transformFile("filename.js", options, function (err, result) { }); ``` -## babel.transformFileSync(filename: string, [options?](/docs/usage/options): Object) +## babel.transformFileSync(filename: string, [options?](/docs/usage/api/#options): Object) Synchronous version of `babel.transformFile`. Returns the transformed contents of the `filename`. @@ -63,7 +63,7 @@ babel.transformFileSync(filename, options) // => { code, map, ast } babel.transformFileSync("filename.js", options).code; ``` -## babel.transformFromAst(ast: Object, code?: string, [options?](/docs/usage/options): Object) +## babel.transformFromAst(ast: Object, code?: string, [options?](/docs/usage/api/#options): Object) Given, an [AST](https://astexplorer.net/), transform it. From d8b92f2bed1818dd9446ad2fcf218e18869b202d Mon Sep 17 00:00:00 2001 From: Marek Suscak Date: Tue, 6 Dec 2016 15:49:58 +0100 Subject: [PATCH 07/10] rename learn-js back to learn-es2015. --- _data/navigation.yml | 2 +- learn-js.md => learn-es2015.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename learn-js.md => learn-es2015.md (99%) diff --git a/_data/navigation.yml b/_data/navigation.yml index cd737219af..6281a6cb61 100644 --- a/_data/navigation.yml +++ b/_data/navigation.yml @@ -1,5 +1,5 @@ - title: Learn ES2015 - url: /learn-js/ + url: /learn-es2015/ - title: Docs url: /docs subnav: diff --git a/learn-js.md b/learn-es2015.md similarity index 99% rename from learn-js.md rename to learn-es2015.md index 364b69516e..eaecb3ef5a 100644 --- a/learn-js.md +++ b/learn-es2015.md @@ -2,7 +2,7 @@ layout: docs title: Learn ES2015 description: A detailed overview of ECMAScript 2015 features. Based on Luke Hoban's es6features repo. -permalink: /learn-js/ +permalink: /learn-es2015/ redirect_from: - /docs/learn-es6/ - /docs/learn-es2015/ From cd0895115cfcdb27985103525e92a60de2d2325b Mon Sep 17 00:00:00 2001 From: Marek Suscak Date: Tue, 6 Dec 2016 16:04:31 +0100 Subject: [PATCH 08/10] Bring back warning from the old browser page. --- _includes/tools/browser/install.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/_includes/tools/browser/install.md b/_includes/tools/browser/install.md index 6c83c6f955..14277478fc 100644 --- a/_includes/tools/browser/install.md +++ b/_includes/tools/browser/install.md @@ -1,3 +1,14 @@ +
    +

    + +

    +

    + 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 setup build systems + for more information. +

    +
    You can use [babel/babel-standalone](https://github.com/babel/babel-standalone#usage) as a precompiled version of babel or run a bundler on babel yourself. From 000eb414a15f0aa298bf8370add2a896650a8c25 Mon Sep 17 00:00:00 2001 From: Marek Suscak Date: Tue, 6 Dec 2016 16:09:01 +0100 Subject: [PATCH 09/10] Rephrase editors syntax highlighting intro section. --- docs/editors.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/editors.md b/docs/editors.md index 8f14f7131d..f882615cf8 100644 --- a/docs/editors.md +++ b/docs/editors.md @@ -7,9 +7,9 @@ permalink: /docs/editors ## Syntax Highlighting -Most popular editors these days do support ES2015+ syntax highlighting. -Some of them require installing additional extensions while some others -don't. This guide should help you get the syntax highlighting to work. +These days, many popular editors support ES2015+ syntax highlighting +out of the box, while some require installing additional extensions. +This guide should help you get the syntax highlighting to work. If you're looking for more advanced integrations, you may want to take a look at the [Setup](/docs/setup) guide. From dc92f9cae42ca648b2ef95c592fe80e712f3ffad Mon Sep 17 00:00:00 2001 From: Marek Suscak Date: Tue, 6 Dec 2016 17:48:15 +0100 Subject: [PATCH 10/10] Fix a typo. --- docs/editors.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/editors.md b/docs/editors.md index f882615cf8..c457e9a77f 100644 --- a/docs/editors.md +++ b/docs/editors.md @@ -1,7 +1,7 @@ --- layout: docs title: Editors -description: Learn how to use Babel in the editor of choice +description: Learn how to use Babel in your editor of choice permalink: /docs/editors ---