Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

7.6.0 #2099

Merged
merged 3 commits into from
Sep 13, 2019
Merged

7.6.0 #2099

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion website/versioned_docs/version-7.0.0/config-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Babel has two parallel config file formats, which can be used together, or indep

## Project-wide configuration

New in Babel 7.x, Babel has as concept of a ["root"](options.md#root) directory, which defaults
New in Babel 7.x, Babel has a concept of a ["root"](options.md#root) directory, which defaults
to the current working directory. For project-wide configuration, Babel will automatically search
for a `"babel.config.js"` in this root directory. Alternatively, users can use an explicit
["configFile"](options.md#configfile) value to override the default config file search behavior.
Expand Down
8 changes: 4 additions & 4 deletions website/versioned_docs/version-7.0.0/core.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ Given an [AST](https://astexplorer.net/), transform it.

```js
const sourceCode = "if (true) return;";
const parsedAst = babel.parse(sourceCode, { allowReturnOutsideFunction: true });
const parsedAst = babel.parse(sourceCode, { parserOpts: { allowReturnOutsideFunction: true } });
babel.transformFromAst(parsedAst, sourceCode, options, function(err, result) {
const { code, map, ast } = result;
});
Expand All @@ -167,7 +167,7 @@ Given an [AST](https://astexplorer.net/), transform it.

```js
const sourceCode = "if (true) return;";
const parsedAst = babel.parse(sourceCode, { allowReturnOutsideFunction: true });
const parsedAst = babel.parse(sourceCode, { parserOpts: { allowReturnOutsideFunction: true } });
const { code, map, ast } = babel.transformFromAstSync(parsedAst, sourceCode, options);
```

Expand All @@ -179,9 +179,9 @@ Given an [AST](https://astexplorer.net/), transform it.

```js
const sourceCode = "if (true) return;";
babel.parseAsync(sourceCode, { allowReturnOutsideFunction: true })
babel.parseAsync(sourceCode, { parserOpts: { allowReturnOutsideFunction: true } })
.then(parsedAst => {
return babel.transformFromAstSync(parsedAst, sourceCode, options);
return babel.transformFromAstAsync(parsedAst, sourceCode, options);
})
.then(({ code, map, ast }) => {
// ...
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ import { addSideEffect } from "@babel/helper-module-imports";
addSideEffect(path, 'source');
```

### `import { named } from "source"`
### `import { named as _named } from "source"`

```js
import { addNamed } from "@babel/helper-module-imports";
// if the hintedName isn't set, the function will gennerate a uuid as hintedName itself such as '_named'
addNamed(path, 'named', 'source');
```

Expand Down
3 changes: 2 additions & 1 deletion website/versioned_docs/version-7.0.0/learn.md
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,8 @@ building global apps in JavaScript.
"𠮷".match(/./u)[0].length == 2

// new form
"\u{20BB7}" == "𠮷" == "\uD842\uDFB7"
"\u{20BB7}" == "𠮷"
"𠮷" == "\uD842\uDFB7"

// new String ops
"𠮷".codePointAt(0) == 0x20BB7
Expand Down
2 changes: 1 addition & 1 deletion website/versioned_docs/version-7.0.0/node.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ npx babel-node test
>
> ```sh
> NODE_NO_READLINE=1 rlwrap --always-readline npx babel-node
>
> ```

### Usage

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ const profile = (

import Preact from 'preact';

const profile = h("div", null,
const profile = Preact.h("div", null,
Preact.h("img", { src: "avatar.png", className: "profile" }),
Preact.h("h3", null, [user.firstName, user.lastName].join(" "))
);
Expand Down
2 changes: 1 addition & 1 deletion website/versioned_docs/version-7.0.0/runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ This is meant to be used as a runtime `dependency` along with the Babel plugin [

## Why

Sometimes Babel may inject some code in the output that is the same and thus can be potentially re-used.
Sometimes Babel may inject some code in the output that is the same across files, and thus can be potentially re-used.

For example, with the class transform (without loose mode):

Expand Down
2 changes: 1 addition & 1 deletion website/versioned_docs/version-7.0.0/template.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ const fn = template`
`;

const ast = fn({
IMPORT_NAME: t.identifier("myModule");
IMPORT_NAME: t.identifier("myModule"),
});

console.log(generate(ast).code);
Expand Down
2 changes: 1 addition & 1 deletion website/versioned_docs/version-7.0.0/usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ Now the `env` preset will only load transformation plugins for features that are

The [@babel/polyfill](polyfill.md) module includes [core-js](https://github.com/zloirock/core-js) and a custom [regenerator runtime](https://github.com/facebook/regenerator/blob/master/packages/regenerator-runtime/runtime.js) to emulate a full ES2015+ environment.

This means you can use new built-ins like `Promise` or `WeakMap`, static methods like `Array.from` or `Object.assign`, instance methods like `Array.prototype.includes`, and generator functions (provided you use the [regenerator](plugin-transform-regenerator.md) plugin). The polyfill adds to the global scope as well as native prototypes like `String` in order to do this.
This means you can use new built-ins like `Promise` or `WeakMap`, static methods like `Array.from` or `Object.assign`, instance methods like `Array.prototype.includes`, and generator functions (when used alongside the regenerator plugin). The polyfill adds to the global scope as well as native prototypes like `String` in order to do this.

For library/tool authors this may be too much. If you don't need the instance methods like `Array.prototype.includes` you can do without polluting the global scope altogether by using the [transform runtime](plugin-transform-runtime.md) plugin instead of `@babel/polyfill`.

Expand Down
2 changes: 1 addition & 1 deletion website/versioned_docs/version-7.0.0/v7-migration-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ See Babylon's [plugin options](parser.md#plugins).

It has been renamed to align with the `legacy` option of `@babel/plugin-proposal-decorators`. A new `decorators` plugin has been implemented, which implements the new decorators proposal.

The two versions of the proposals have different syntaxes, so it is highly reccomended to use `decorators-legacy` until the new semantics are implemented by Babel.
The two versions of the proposals have different syntaxes, so it is highly recommended to use `decorators-legacy` until the new semantics are implemented by Babel.

> Removed `classConstructorCall` plugin [#291](https://github.com/babel/babylon/pull/291) ![low](https://img.shields.io/badge/risk%20of%20breakage%3F-low-yellowgreen.svg)

Expand Down
2 changes: 1 addition & 1 deletion website/versioned_docs/version-7.1.0/config-files.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Babel has two parallel config file formats, which can be used together, or indep

## Project-wide configuration

New in Babel 7.x, Babel has as concept of a ["root"](options.md#root) directory, which defaults
New in Babel 7.x, Babel has a concept of a ["root"](options.md#root) directory, which defaults
to the current working directory. For project-wide configuration, Babel will automatically search
for a `"babel.config.js"` in this root directory. Alternatively, users can use an explicit
["configFile"](options.md#configfile) value to override the default config file search behavior.
Expand Down
2 changes: 1 addition & 1 deletion website/versioned_docs/version-7.4.0/template.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ const fn = template`
`;

const ast = fn({
IMPORT_NAME: t.identifier("myModule");
IMPORT_NAME: t.identifier("myModule"),
});

console.log(generate(ast).code);
Expand Down
218 changes: 218 additions & 0 deletions website/versioned_docs/version-7.4.0/usage.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
---
id: version-7.4.0-usage
title: Usage Guide
original_id: usage
---

There are quite a few tools in the Babel toolchain that try to make it easy for you to use Babel whether you're an "end-user" or building an integration of Babel itself. This will be a quick introduction to those tools and you can read more about them in the "Usage" section of the docs.

> If you're using a framework, the work of configuring Babel might be different or actually already handled for you. Check out our [interactive setup guide](/setup.html) instead.

## Overview

This guide will show you how to compile your JavaScript application code that uses ES2015+ syntax into code that works in current browsers. That will involve both transforming new syntax and polyfilling missing features.

The entire process to set this up involves:

1. Running these commands to install the packages:

```sh
npm install --save-dev @babel/core @babel/cli @babel/preset-env
npm install --save @babel/polyfill
```

2. Creating a config file named `babel.config.js` in the root of your project with this content:

```js
const presets = [
[
"@babel/env",
{
targets: {
edge: "17",
firefox: "60",
chrome: "67",
safari: "11.1",
},
useBuiltIns: "usage",
},
],
];

module.exports = { presets };
```

> The browsers list above is just an arbitrary example. You will have to adapt it for the browsers you want to support.

3. And running this command to compile all your code from the `src` directory to `lib`:

```sh
./node_modules/.bin/babel src --out-dir lib
```

> You can use the npm package runner that comes with npm@5.2.0 to shorten that command by replacing `./node_modules/.bin/babel` with `npx babel`

Read on for a step-by-step explanation of how this works and an introduction to each of the tools used.

## Basic usage with CLI

All the Babel modules you'll need are published as separate npm packages scoped under `@babel` (since version 7). This modular design allows for various tools each designed for a specific use case. Here we'll look at `@babel/core` and `@babel/cli`.

### Core Library

The core functionality of Babel resides at the [@babel/core](core.md) module. After installing it:

```sh
npm install --save-dev @babel/core
```

you can `require` it directly in your JavaScript program and use it like this:

```js
const babel = require("@babel/core");

babel.transform("code", optionsObject);
```

As an end-user though, you'll probably want to install other tools that serve as an interface to `@babel/core` and integrate well with your development process. Even so, you might still want to check its documentation page to learn about the options, most of which can be set from the other tools as well.

### CLI tool

[@babel/cli](cli.md) is a tool that allows you to use babel from the terminal. Here's the installation command and a basic usage example:

```sh
npm install --save-dev @babel/core @babel/cli

./node_modules/.bin/babel src --out-dir lib
```

This will parse all the JavaScript files in the `src` directory, apply any transformations we have told it to, and output each file to the `lib` directory. Since we haven't told it to apply any transformations yet, the output code will be identical to the input (exact code styling is not preserved). We can specify what transformations we want by passing them as options.

We used the `--out-dir` option above. You can view the rest of the options accepted by the cli tool by running it with `--help`. But the most important to us right now are `--plugins` and `--presets`.

## Plugins & Presets

Transformations come in the form of plugins, which are small JavaScript programs that instruct Babel on how to carry out transformations to the code. You can even write your own plugins to apply any transformations you want to your code. To transform ES2015+ syntax into ES5 we can rely on official plugins like `@babel/plugin-transform-arrow-functions`:

```sh
npm install --save-dev @babel/plugin-transform-arrow-functions

./node_modules/.bin/babel src --out-dir lib --plugins=@babel/plugin-transform-arrow-functions
```

Now any arrow functions in our code will be transformed into ES5 compatible function expressions:

```js
const fn = () => 1;

// converted to

var fn = function fn() {
return 1;
};
```

That's a good start! But we also have other ES2015+ features in our code that we want transformed. Instead of adding all the plugins we want one by one, we can use a "preset" which is just a pre-determined set of plugins.

Just like with plugins, you can create your own presets too to share any combination of plugins you need. For our use case here, there's an excellent preset named `env`.

```sh
npm install --save-dev @babel/preset-env

./node_modules/.bin/babel src --out-dir lib --presets=@babel/env
```

Without any configuration, this preset will include all plugins to support modern JavaScript (ES2015, ES2016, etc.). But presets can take options too. Rather than passing both cli and preset options from the terminal, let's look at another way of passing options: configuration files.

## Configuration

> There are a few different ways to use configuration files depending on your needs. Be sure to read our in-depth guide on how to [configure Babel](configuration.md) for more information.

For now, let's create a file called `babel.config.js` with the following content:

```js
const presets = [
[
"@babel/env",
{
targets: {
edge: "17",
firefox: "60",
chrome: "67",
safari: "11.1",
},
},
],
];

module.exports = { presets };
```

Now the `env` preset will only load transformation plugins for features that are not available in our target browsers. We're all set for syntax. Let's look at polyfills next.

## Polyfill

> 🚨 As of Babel 7.4.0, this package has been deprecated in favor of directly including `core-js/stable` (to polyfill ECMAScript features) and `regenerator-runtime/runtime` (needed to use transpiled generator functions):
> ```js
> import "core-js/stable";
> import "regenerator-runtime/runtime";
> ```

The [@babel/polyfill](polyfill.md) module includes [core-js](https://github.com/zloirock/core-js) and a custom [regenerator runtime](https://github.com/facebook/regenerator/blob/master/packages/regenerator-runtime/runtime.js) to emulate a full ES2015+ environment.

This means you can use new built-ins like `Promise` or `WeakMap`, static methods like `Array.from` or `Object.assign`, instance methods like `Array.prototype.includes`, and generator functions (when used alongside the regenerator plugin). The polyfill adds to the global scope as well as native prototypes like `String` in order to do this.

For library/tool authors this may be too much. If you don't need the instance methods like `Array.prototype.includes` you can do without polluting the global scope altogether by using the [transform runtime](plugin-transform-runtime.md) plugin instead of `@babel/polyfill`.

To go one step further, if you know exactly what features you need polyfills for, you can require them directly from [core-js](https://github.com/zloirock/core-js#commonjs).

Since we're building an application we can just install `@babel/polyfill`:

```sh
npm install --save @babel/polyfill
```

> Note the `--save` option instead of `--save-dev` as this is a polyfill that needs to run before your source code.

Now luckily for us, we're using the `env` preset which has a `"useBuiltIns"` option that when set to `"usage"` will practically apply the last optimization mentioned above where you only include the polyfills you need. With this new option the configuration changes like this:

```js
const presets = [
[
"@babel/env",
{
targets: {
edge: "17",
firefox: "60",
chrome: "67",
safari: "11.1",
},
useBuiltIns: "usage",
},
],
];

module.exports = { presets };
```

Babel will now inspect all your code for features that are missing in your target environments and include only the required polyfills. For example this code:

```js
Promise.resolve().finally();
```

would turn into this (because Edge 17 doesn't have `Promise.prototype.finally`):

```js
require("core-js/modules/es.promise.finally");

Promise.resolve().finally();
```

If we weren't using the `env` preset with the `"useBuiltIns"` option set to `"usage"` we would've had to require the full polyfill _only once_ in our entry point before any other code.

## Summary

We used `@babel/cli` to run Babel from the terminal, `@babel/polyfill` to polyfill all the new JavaScript features, and the `env` preset to only include the transformations and polyfills for the features that we use and that are missing in our target browsers.

For more information on setting up Babel with your build system, IDE, and more, check out our [interactive setup guide](/setup.html).