## 1. Project Overview & Quickstart (benjamn/polyfill)

# polyfill

Open-source repository benjamn/polyfill

### Repository Details
- **Repository:** [benjamn/polyfill](https://github.com/benjamn/polyfill)
- **Primary Language:** Code

*Note: High-volume repository documentation is actively indexed and synchronized by YakaAI.*

## 2. Official Technical Reference & Guides (benjamn/website)

## File: README.md

# [babel/website](https://babeljs.io)

This is the source for the [babeljs.io](https://babeljs.io) website; feel free to suggest changes to our docs!

- Current: `master` branch is deployed to https://babeljs.io
- Old: `old-site` branch is deployed to https://old.babeljs.io

### Setup

```bash
$ git clone git@github.com:babel/website.git
$ cd website
$ yarn && yarn bootstrap
```

- Just run `yarn start` next time (check the package.json for scripts).

### Contributing to the website

To keep documentation in sync across all of Babel's packages, the docs are now directly located in this repository. The READMEs in [`babel/babel`](https://github.com/babel/babel) are [auto generated](https://github.com/babel/babel/blob/master/scripts/generators/readmes.js) and point to this documentation.

You might want to make yourself familiar with [docusaurus](https://docusaurus.io/docs/en/installation) to make significant changes to the website. If you only want to make content changes you just need to know about versioned docs.

#### Versioned docs

- `/docs` - the files in here are responsible for the "next" version at https://babeljs.io/docs/en/next.
- `/website/versioned_docs/version-*` - these are the docs for the past versions, the latest one being the currently published version at https://babeljs.io/docs/en

After making your changes to the markdown files in the `/docs` folder, a git hook script will suggest files from the past versions folders that you might also need to apply your changes to.

#### Looking for support?

For questions and support on contributing please join our [Slack community](https://slack.babeljs.io/), channel `#website` or directly [here](https://babeljs.slack.com/messages/website).

---

## File: docs/babelconfigjs.md

---
title: babel.config.js
id: babelconfigjs
---

This documentation has been moved to [project-wide configuration docs](config-files.md#project-wide-configuration).

---

## File: docs/babelrc.md

---
title: .babelrc
id: babelrc
---

This documentation has been moved to [file-relative configuration docs](config-files.md#file-relative-configuration).

---

## File: docs/caveats.md

---
title: Caveats
id: caveats
---

## Polyfills

In order for certain features to work they require certain polyfills. You can satisfy **all**
Babel feature requirements by using [@babel/polyfill](polyfill.md).

You may alternatively/selectively include what you need:

| Feature                     | Requirements                                                                          |
| --------------------------- | ------------------------------------------------------------------------------------- |
| Async functions, Generators | [regenerator runtime](https://github.com/facebook/regenerator/tree/master/packages/regenerator-runtime) |
| Array destructuring, For Of | `Symbol`, `prototype[Symbol.iterator]`                                                |
| Spread                      | `Array.from`                                                                          |

There is also the `loose` option for some of these plugins.

## Classes

Built-in classes such as `Date`, `Array`, `DOM` etc cannot be properly subclassed
due to limitations in ES5 (for the [transform-classes](plugin-transform-classes.md) plugin).
You can try to use [babel-plugin-transform-builtin-extend](https://github.com/loganfsmyth/babel-plugin-transform-builtin-extend) based on `Object.setPrototypeOf` and `Reflect.construct`, but it also has some limitations.

## ES5

Since Babel assumes that your code will run in an ES5 environment it uses ES5
functions. So if you're using an environment that has limited or no support for
ES5 such as lower versions of IE then using [@babel/polyfill](polyfill.md) will add support for these methods.

## Internet Explorer

### Classes (10 and below)

If you're inheriting from a class then static properties are inherited from it
via [\_\_proto\_\_](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/proto),
this is widely supported but you may run into problems with much older browsers.

**NOTE:** `__proto__` is not supported on IE <= 10 so static properties
**will not** be inherited. See the
[protoToAssign](plugin-transform-proto-to-assign.md) for a possible work
around.

For classes that have `super`s, the super class won't resolve correctly. You can
get around this by enabling the `loose` option in the [transform-classes](plugin-transform-classes.md) plugin.

### 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 usage 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).

#### Modules

By default, when using modules with Babel a non-enumerable `__esModule` property
is exported. This is done through the use of `Object.defineProperty` which is
unsupported in IE8 and below. A workaround for this is to enable the `loose` option in your corresponding module plugin.

---

## File: docs/cli.md

---
id: babel-cli
title: @babel/cli
sidebar_label: cli
---

Babel comes with a built-in CLI which can be used to compile files from the command line.

In addition, various entry point scripts live in the top-level package at `@babel/cli/bin`. There is a shell-executable utility script, `babel-external-helpers.js`, and the main Babel cli script, `babel.js`.

## Install

While you _can_ install Babel CLI globally on your machine, it's much better
to install it **locally** project by project.

There are two primary reasons for this.

1. Different projects on the same machine can depend on different versions of
     Babel allowing you to update them individually.
2. Not having an implicit dependency on the environment you are working in
     makes your project far more portable and easier to setup.

We can install Babel CLI locally by running:

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

> **Note:** If you do not have a `package.json`, create one before installing. This will ensure proper interaction with the `npx` command.

After that finishes installing, your `package.json` file should include:

```diff
{
  "devDependencies": {
+   "@babel/cli": "^7.0.0",
+   "@babel/core": "^7.0.0"
  }
}
```

## Usage

```sh
babel script.js
```

> **Note:** These instructions use the excellent [npx](https://medium.com/@maybekatz/introducing-npx-an-npm-package-runner-55f7d4bd282b) command to run the locally installed executables. You can drop it inside of an [npm run script](https://docs.npmjs.com/cli/run-script) or you may instead execute with the relative path instead. `./node_modules/.bin/babel`

### Compile Files

Compile the file `script.js` and **output to stdout**.

```sh
npx babel script.js
# output...
```

If you would like to **output to a file** you may use `--out-file` or `-o`.

```sh
npx babel script.js --out-file script-compiled.js
```

To compile a file **every time that you change it**, use the `--watch` or `-w` option:

```sh
npx babel script.js --watch --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
npx babel script.js --out-file script-compiled.js --source-maps
```

Or, if you'd rather have **inline source maps**, use `--source-maps inline` instead.

```sh
npx babel script.js --out-file script-compiled.js --source-maps inline
```

### Compile Directories

Compile the entire `src` directory and output it to the `lib` directory by using either `--out-dir` or `-d`. This doesn't overwrite any other files or directories in `lib`.

```sh
npx babel src --out-dir lib
```

Compile the entire `src` directory and output it as a single concatenated file.

```sh
npx babel src --out-file script-compiled.js
```

### Ignore files

Ignore spec and test files

```sh
npx babel src --out-dir lib --ignore "src/**/*.spec.js","src/**/*.test.js"
```

### Copy files

Copy files that will not be compiled

```sh
npx babel src --out-dir lib --copy-files
```

### Piping Files

Pipe a file in via stdin and output it to `script-compiled.js`

```sh
npx babel --out-file script-compiled.js < script.js
```

### Using Plugins

Use the `--plugins` option to specify plugins to use in compilation

```sh
npx babel script.js --out-file script-compiled.js --plugins=@babel/proposal-class-properties,@babel/transform-modules-amd
```

### Using Presets

Use the `--presets` option to specify plugins to use in compilation

```sh
npx babel script.js --out-file script-compiled.js --presets=@babel/preset-env,@babel/flow
```

### Ignoring .babelrc

Ignore the configuration from the project's `.babelrc` file and use the cli options e.g. for a custom build

```sh
npx babel --no-babelrc script.js --out-file script-compiled.js --presets=es2015,react
```

### Advanced Usage

There are many more options available, see [options](options.md), `babel --help` and other sections for more information.

---

## File: docs/code-frame.md

---
id: babel-code-frame
title: @babel/code-frame
sidebar_label: code-frame
---

## Install

```sh
npm install --save-dev @babel/code-frame
```

## Usage

```js
import { codeFrameColumns } from '@babel/code-frame';

const rawLines = `class Foo {
  constructor()
}`;
const location = { start: { line: 2, column: 16 } };

const result = codeFrameColumns(rawLines, location, { /* options */ });

console.log(result);
```

```
  1 | class Foo {
> 2 |   constructor()
    |                ^
  3 | }
```

If the column number is not known, you may omit it.

You can also pass an `end` hash in `location`.

```js
import { codeFrameColumns } from '@babel/code-frame';

const rawLines = `class Foo {
  constructor() {
    console.log("hello");
  }
}`;
const location = { start: { line: 2, column: 17 }, end: { line: 4, column: 3 } };

const result = codeFrameColumns(rawLines, location, { /* options */ });

console.log(result);
```

```
  1 | class Foo {
> 2 |   constructor() {
    |                 ^
> 3 |     console.log("hello");
    | ^^^^^^^^^^^^^^^^^^^^^^^^^
> 4 |   }
    | ^^^
  5 | };
```

## Options

### `highlightCode`

`boolean`, defaults to `false`.

Toggles syntax highlighting the code as JavaScript for terminals.


### `linesAbove`

`number`, defaults to `2`.

Adjust the number of lines to show above the error.

### `linesBelow`

`number`, defaults to `3`.

Adjust the number of lines to show below the error.

### `forceColor`

`boolean`, defaults to `false`.

Enable this to forcibly syntax highlight the code as JavaScript (for non-terminals); overrides `highlightCode`.

### `message`

`string`, otherwise nothing

Pass in a string to be displayed inline (if possible) next to the highlighted
location in the code. If it can't be positioned inline, it will be placed above
the code frame.

```
1 | class Foo {
> 2 |   constructor()
  |                ^ Missing {
3 | };
```

## Upgrading from prior versions

Prior to version 7, the only API exposed by this module was for a single line and optional column pointer. The old API will now log a deprecation warning.

The new API takes a `location` object, similar to what is available in an AST.

This is an example of the deprecated (but still available) API:

```js
import codeFrame from '@babel/code-frame';

const rawLines = `class Foo {
  constructor()
}`;
const lineNumber = 2;
const colNumber = 16;

const result = codeFrame(rawLines, lineNumber, colNumber, { /* options */ });

console.log(result);
```

To get the same highlighting using the new API:

```js
import { codeFrameColumns } from '@babel/code-frame';

const rawLines = `class Foo {
  constructor() {
    console.log("hello");
  }
}`;
const location = { start: { line: 2, column: 16 } };

const result = codeFrameColumns(rawLines, location, { /* options */ });

console.log(result);
```

---

## File: docs/config-files.md

---
title: Config Files
id: config-files
---

## Configuration File Types

Babel has two parallel config file formats, which can be used together, or independently.

* Project-wide configuration
* File-relative configuration
  * `.babelrc` (and `.babelrc.js`) files
  * `package.json` files with a `"babel"` key


## Project-wide configuration

New in Babel 7.x, Babel has as 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.

Because project-wide config files are separated from the physical location of the config
file, they can be ideal for configuration that must apply broadly, even allowing
plugins and presets to easily apply to files in `node_modules` or in symlinked packages,
which were traditionally quite painful to configure in Babel 6.x.

The primary downside of this project-wide config is that, because it relies on the working
directory, it can be more painful to use in monorepos if the working directory is not the monorepo root.
See the [monorepo](#monorepos) documentation for examples of how to use config files in that context.

Project-wide configs can also be disabled by setting ["configFile"](options.md#configfile) to `false`.

## File-relative configuration

Babel loads `.babelrc` (and `.babelrc.js` / `package.json#babel`) files by searching up the
directory structure starting from the ["filename"](options.md#filename) being compiled (limited by the caveats below).
This can be powerful because it allows you to create independent configurations for subsections of
a package. File-relative configurations are also [merged](options.md#merging) over top of
project-wide config values, making them potentially useful for specific overrides, though that can
also be accomplished through ["overrides"](options.md#overrides).

There are a few edge cases to consider when using a file-relative config:
* Searching will stop once a directory containing a `package.json` is found, so a relative config
  only applies within a single package.
* The ["filename"](options.md#filename) being compiled must be inside of
  ["babelrcRoots"](options.md#babelrcroots) packages, or else searching will be skipped entirely.

These caveats mean that:
* `.babelrc` files _only_ apply to files within their own package
* `.babelrc` files in packages that aren't Babel's 'root' are ignored unless you opt in
  with ["babelrcRoots"](options.md#babelrcroots).

See the [monorepo](#monorepos) documentation for more discussion on how to configure monorepos that have many packages.

File-relative configs can also be disabled by setting ["babelrc"](options.md#babelrc) to `false`.

### 6.x vs 7.x `.babelrc` loading

Users coming from Babel 6.x will likely trip up on these two edge cases, which are new in Babel 7.x.
These two restrictions were added to address common footguns in Babel 6.x:

* `.babelrc` files applied to `node_modules` dependencies, often unexpectedly.
* `.babelrc` files _failed_ to apply to symlinked `node_modules` when people expected them to behave like normal dependencies.
* `.babelrc` files _in_ `node_modules` dependencies would be detected, even though the plugins and
  presets inside they were generally not installed, and may not even be valid in the version of
  Babel compiling the file.

These cases will _primarily_ cause issues for users with a monorepo structure, because if you
have
```text
.babelrc
packages/
  mod1/
    package.json
    src/index.js
  mod2/
    package.json
    src/index.js
```
the config will now be entirely ignored, because it is across a package boundary.

One alternative would be to create a `.babelrc` in each sub-package that uses ["extends"](options.md#extends) as
```json
{ "extends": "../../.babelrc" }
```
Unfortunately, this approach can be a bit repetitive, and depending on how Babel is being used,
could require setting ["babelrcRoots"](options.md#babelrcroots).

Given that, it may be more desirable to rename the `.babelrc` to be a
[project-wide "babel.config.js"](#project-wide-configuration). As mentioned in the project-wide
section above, this may then require explicitly setting ["configFile"](options.md#configfile)
since Babel will not find the config file if the working directory isn't correct.


## Monorepos

Monorepo-structured repositories usually contain many packages, which means that they frequently
run into the caveats mentioned in [file-relative configuration](#file-relative-configuration)
and config file loading in general. This section is aimed at helping users understand how
to approach monorepo configuration.

With monorepo setups, the core thing to understand is that Babel treats your working directory
as its logical ["root"](options.md#root), which causes problems if you want to run Babel
tools within a specific sub-package without having Babel apply to the repo as a whole.

Separately, it is also important to decide if you want to use [`.babelrc`](#file-relative-configuration)
files or just a central [`babel.config.js`](#project-wide-configuration). [`.babelrc`](#file-relative-configuration)
files are not required for subfolder-specific configuration like they were in Babel 6, so
often they are not needed in Babel 7, in favor of a [`babel.config.js`](#project-wide-configuration).


### Root `babel.config.js` files

The first step in any monorepo structure should be to create a
[`babel.config.js`](#project-wide-configuration) file in repository root. This
establishes Babel's core concept of the base directory of your repository. Even if you want to use
[`.babelrc`](#file-relative-configuration) files to configure each separate package, it is important
to have as a place for repo-level options.

You can often place all of your repo configuration in the root [`babel.config.js`](#project-wide-configuration).
With ["overrides"](options.md#overrides), you can easily specify configuration that only applies to
certain subfolders of your repository, which can often be easier to follow than creating many
`.babelrc` files across the repo.

The first issue you'll likely run into is that by default, Babel expects to load [`babel.config.js`](#project-wide-configuration)
files from the directory set as its ["root"](options.md#root), which means that if you create
a [`babel.config.js`](#project-wide-configuration), but run Babel inside an individual package, e.g.

```bash
cd packages/some-package;
babel src -d dist
```
the ["root"](options.md#root) Babel is using in that context is _not_ your monorepo root,
and it won't be able to find the [`babel.config.js`](#project-wide-configuration) file.

If all of your build scripts run relative to your repository root, things should already work, but if
you are running your Babel compilation process from within a subpackage, you need to tell Babel where
to look for the config. There are a few ways to do that, but the recommended way is
the ["rootMode"](options.md#rootmode) option with `"upward"`, which will make Babel search from
the working directory upward looking for your [`babel.config.js`](#project-wide-configuration) file,
and will use its location as the ["root"](options.md#root) value.

One helpful way to test if your config is being detected is to place a `console.log()` call
inside of it. Since it is a JS file, the log will execute the first time Babel loads it.

How you set this value varies by project, but here are a few examples:

#### CLI
```bash
babel --root-mode upward src -d lib
```

#### @babel/register
```js
require("@babel/register")({
  rootMode: "upward"
});
```

#### Webpack
```js
module: {
  rules: [{
    loader: "babel-loader",
    options: {
      rootMode: "upward",
    }
  }]
}
```

#### Jest
Jest is often installed at the root of the monorepo and may not require configuration,
but if it is installed per-package it can unfortunately be more complex to configure.

The main part is creating a custom jest transformer file that wraps `babel-jest`'s default
behavior in order to set the option, e.g.
```js
module.exports = require("babel-jest").createTransformer({
  rootMode: "upward",
});
```
and with that saved somewhere, you'd then use that file in the place of `babel-jest` in
your Jest options via the [transform option](https://jestjs.io/docs/en/configuration#transform-object-string-string):
```json
"transform": {
  "^.+\\.jsx?$": "./path/to/wrapper.js"
},
```
so all JS files will be processed with your version of `babel-jest` with the option enabled.

#### Others

There are tons of tools, but at the core of it is that they need the `rootMode` option enabled
if the working directory is not already the monorepo root.


### Subpackage `.babelrc` files

Similar to the the way `babel.config.js` files are required to be in the ["root"](options.md#root),
`.babelrc` files must be in the root _package_, by default. This means that, the same way the
working directory affects `babel.config.js` loading, it also affects `.babelrc` loading.

Assuming you've already gotten your `babel.config.js` file loaded properly as discussed above,
Babel will only process `.babelrc` files inside that root package (and not subpackages),
so given for instance

```text
package.json
babel.config.js
packages/
  mod/
    package.json
    .babelrc
    index.js
```
compiling the `packages/mod/index.js` file will not load `packages/mod/.babelrc` because
this `.babelrc` is within a sub-package, not the root package.

To enable processing of that `.babelrc`, you will want to use the ["babelrcRoots"](options.md#babelrcroots)
option from inside your `babel.config.js` file to do

```js
babelrcRoots: [
  ".",
  "packages/*",
],
```
so that Babel will consider all `packages/*` packages as allowed to load `.babelrc` files,
along with the original repo root.


## Config Format

The format of individual config files themselves separates into JS files vs [JSON5](https://json5.org/) files.

### JSON5

Any file that isn't a `.js` file will be parsed as JSON5 and should contain an object matching
the [options](options.md) format that Babel accepts.

### JavaScript

Any `.js` file will be `require()`ed and should export either a configuration object, or a function
that will return a configuration object when called. The main benefit being that users can include
JS logic to build up their config structures, potentially allowing config logic to be shared
more easily. `.js` files can be used as [project-wide configuration](#project-wide-configuration) or
via `.babelrc.js` files for [file-relative configuration](#file-relative-configuration).

Function-returning configs are given a few special powers because they can access an API exposed
by Babel itself. See [Config Function API](#config-function-api) for more information.

## Config Function API

JS config files may export a function that will be passed config function API:

```js
module.exports = function(api) {
  return {};
}
```

The `api` object exposes everything Babel itself exposes from its index module, along with
config-file specific APIs:

### `api.version`

Type: `string`

The version string for the Babel version that is loading the config file.

### `api.cache`

JS configs are great because they can compute a config on the fly, but the downside
there is that it makes caching harder. Babel wants to avoid re-executing the
config function every time a file is compiled, because then it would also need to
re-execute any plugin and preset functions referenced in that config.

To avoid this, Babel expects users of config functions to tell it how to manage
caching within a config file.

* `api.cache.forever()` - Permacache the computed config and never call the function again.
* `api.cache.never()` - Do not cache this config, and re-execute the function every time.
* `api.cache.using(() => process.env.NODE_ENV)` - Cache based on the value of `NODE_ENV`.
  Any time the `using` callback returns a value other than the one that was expected, the overall
  config function will be called again and a new entry will be added to the cache.
* `api.cache.invalidate(() => process.env.NODE_ENV)` - Cache based on the value of `NODE_ENV`.
  Any time the `using` callback returns a value other than the one that was expected, the overall
  config function will be called again and all entries in the cache will be replaced with the result.
* `api.cache(true)` - Same as `api.cache.forever()`
* `api.cache(false)` - Same as `api.cache.never()`

Since the actual callback result is used to check if the cache entry is valid, it is recommended
that:

* Callbacks should be small and side-effect free.
* Callbacks should return values with the smallest range possible. For example, the
  `.using(() => process.env.NODE_ENV)` usage above is not ideal because it would create an unknown
  number of cache entries depending on how many values of `NODE_ENV` are detected. It would be
  safer to do `.using(() => process.env.NODE_ENV === "development")` because then the cache entry
  can only ever be `true` or `false`.


### `api.env(...)`

Since `NODE_ENV` is a fairly common way to toggle behavior, Babel also includes an API function
meant specifically for that. This API is used as a quick way to check the
["envName"](options.md#envname) that Babel was loaded with, which takes `NODE_ENV` into account
if no other overriding environment is set.

It has a few different forms:

* `api.env("production")` returns `true` if `envName === "production"`.
* `api.env(["development", "test"])` returns `true` if `["development", "test"].includes(envName)`.
* `api.env()` returns the current `envName` string.
* `api.env(envName => envName.startsWith("test-"))` returns `true` if the env starts with "test-".

> **Note:** This function internally makes use of [`api.cache`](#apicache) mentioned above to ensure that Babel is aware that this build depends on a specific `envName`. You should not use it alongside with `api.cache.forever()` or `api.cache.never()`.


### `api.caller(cb)`

This API is used as a way to access the `caller` data that has been passed to Babel.
Since many instances of Babel may be running in the same process with different `caller`
values, this API is designed to automatically configure `api.cache`, the same way `api.env()` does.

The `caller` value is available as the first parameter of the callback function. It is best used
with something like
```js
function isBabelRegister(caller) {
  return !!(caller && caller.name === "@babel/register");
}

module.exports = function(api) {
  const isRegister = api.caller(isBabelRegister);

  return {
    // ...
  };
}
```
to toggle configuration behavior based on a specific environment.


### `api.assertVersion(range)`

While `api.version` can be useful in general, it's sometimes nice to just declare your version.
This API exposes a simple way to do that with:
```js
module.exports = function(api) {
  api.assertVersion("^7.2");

  return {
    // ...
  };
};
```

---

## File: docs/configuration.md

---
id: configuration
title: Configure Babel
---

Babel can be configured! Many other tools have similar configs: ESLint (`.eslintrc`), Prettier (`.prettierrc`).

All Babel API [options](options.md) are allowed. However, if the option requires JavaScript, you may want to use a JavaScript [configuration file](config-files.md).

## What's your use case?

- You want to programmatically create the configuration?
- You want to compile `node_modules`?

> [`babel.config.js`](#babelconfigjs) is for you!

- You have a static configuration that only applies to your simple single package?

> [`.babelrc`](#babelrc) is for you!

- The Guy Fieri is your hero?

> We recommend to use the [`babel.config.js`](config-files.md#project-wide-configuration) format. [Babel itself is using it](https://github.com/babel/babel/blob/master/babel.config.js).

## `babel.config.js`

Create a file called `babel.config.js` with the following content at the root of your project (where the `package.json` is).

```js
module.exports = function (api) {
  api.cache(true);

  const presets = [ ... ];
  const plugins = [ ... ];

  return {
    presets,
    plugins
  };
}
```

Check out the [`babel.config.js` documentation](config-files.md#project-wide-configuration) to see more configuration options.

## `.babelrc`

Create a file called `.babelrc` with the following content in your project.

```json
{
  "presets": [...],
  "plugins": [...]
}
```

Check out the [.babelrc documentation](config-files.md#file-relative-configuration) to see more configuration options.

### `package.json`

Alternatively, you can choose to specify your [`.babelrc`](#babelrc) config from within `package.json` using the `babel` key like so:

```json
{
  "name": "my-package",
  "version": "1.0.0",
  "babel": {
    "presets": [ ... ],
    "plugins": [ ... ],
  }
}
```

### `.babelrc.js`

The configuration is the same as [`.babelrc`](#babelrc), but you can write it using JavaScript.

```js
const presets = [ ... ];
const plugins = [ ... ];

module.exports = { presets, plugins };
```

You are allowed to access any Node.js APIs, for example a dynamic configuration based on the process environment:

```js
const presets = [ ... ];
const plugins = [ ... ];

if (process.env["ENV"] === "prod") {
  plugins.push(...);
}

module.exports = { presets, plugins };
```

## Using the CLI (`@babel/cli`)

```sh
babel --plugins @babel/plugin-transform-arrow-functions script.js
```

Check out the [babel-cli documentation](cli.md) to see more configuration options.

## Using the API (`@babel/core`)

```js
require("@babel/core").transform("code", {
  plugins: ["@babel/plugin-transform-arrow-functions"]
});
```

Check out the [babel-core documentation](core.md) to see more configuration options.

---

## File: docs/core.md

---
id: babel-core
title: @babel/core
sidebar_label: core
---

```javascript
var babel = require("@babel/core");
import { transform } from "@babel/core";
import * as babel from "@babel/core";
```

All transformations will use your local [configuration files](config-files.md).


## transform

> babel.transform(code: string, [options?](#options): Object, callback: Function)

Transforms the passed in `code`. Calling a callback with an object with the generated code,
source map, and AST.

```js
babel.transform(code, options, function(err, result) {
  result; // => { code, map, ast }
});
```

**Example**

```js
babel.transform("code();", options, function(err, result) {
  result.code;
  result.map;
  result.ast;
});
```

> Compat Note:
>
> In Babel 6, this method was synchronous and `transformSync` did not exist. For backward-compatibility, this function will behave synchronously if no callback is given. If you're starting with Babel 7 and need synchronous behavior, please use `transformSync` since this backward-compat may be dropped in future major versions of Babel.

## transformSync

> babel.transformSync(code: string, [options?](#options): Object)

Transforms the passed in `code`. Returning an object with the generated code,
source map, and AST.

```js
babel.transformSync(code, options) // => { code, map, ast }
```

**Example**

```js
var result = babel.transformSync("code();", options);
result.code;
result.map;
result.ast;
```

## transformAsync

> babel.transformAsync(code: string, [options?](#options): Object)

Transforms the passed in `code`. Returning an promise for an object with the
generated code, source map, and AST.

```js
babel.transformAsync(code, options) // => Promise<{ code, map, ast }>
```

**Example**

```js
babel.transformAsync("code();", options).then(result => {
  result.code;
  result.map;
  result.ast;
});
```


## transformFile

> babel.transformFile(filename: string, [options?](#options): Object, callback: Function)

Asynchronously transforms the entire contents of a file.

```js
babel.transformFile(filename, options, callback)
```

**Example**

```js
babel.transformFile("filename.js", options, function (err, result) {
  result; // => { code, map, ast }
});
```


## transformFileSync

> babel.transformFileSync(filename: string, [options?](#options): Object)

Synchronous version of `babel.transformFile`. Returns the transformed contents of
the `filename`.

```js
babel.transformFileSync(filename, options) // => { code, map, ast }
```

**Example**

```js
babel.transformFileSync("filename.js", options).code;
```


## transformFileAsync

> babel.transformFileAsync(filename: string, [options?](#options): Object)

Promise version of `babel.transformFile`. Returns a promise for the transformed
contents of the `filename`.

```js
babel.transformFileAsync(filename, options) // => Promise<{ code, map, ast }>
```

**Example**

```js
babel.transformFileAsync("filename.js", options).then(result => {
  result.code;
});
```


## transformFromAst

> babel.transformFromAst(ast: Object, code?: string, [options?](#options): Object, callback: Function): FileNode | null

Given an [AST](https://astexplorer.net/), transform it.

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

> Compat Note:
>
> In Babel 6, this method was synchronous and `transformFromAstSync` did not exist. For backward-compatibility, this function will behave synchronously if no callback is given. If you're starting with Babel 7 and need synchronous behavior, please use `transformFromAstSync` since this backward-compat may be dropped in future major versions of Babel.


## transformFromAstSync

> babel.transformFromAstSync(ast: Object, code?: string, [options?](#options): Object)

Given an [AST](https://astexplorer.net/), transform it.

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

## transformFromAstAsync

> babel.transformFromAstAsync(ast: Object, code?: string, [options?](#options): Object)

Given an [AST](https://astexplorer.net/), transform it.

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

## parse

> babel.parse(code: string, [options?](#options): Object, callback: Function)

Given some code, parse it using Babel's standard behavior. Referenced presets and
plugins will be loaded such that optional syntax plugins are automatically
enabled.

> Compat Note:
>
> In Babel 7's early betas, this method was synchronous and `parseSync` did not exist. For backward-compatibility,
> this function will behave synchronously if no callback is given. If you're starting with Babel 7 stable
> and need synchronous behavior, please use `parseSync` since this backward-compat may be dropped
> in future major versions of Babel.


## parseSync

> babel.parseSync(code: string, [options?](#options): Object)

Returns an AST.

Given some code, parse it using Babel's standard behavior. Referenced presets and
plugins will be loaded such that optional syntax plugins are automatically
enabled.

## parseAsync

> babel.parseAsync(code: string, [options?](#options): Object)

Returns a promise for an AST.

Given some code, parse it using Babel's standard behavior. Referenced presets and
plugins will be loaded such that optional syntax plugins are automatically
enabled.


## Advanced APIs

Many systems that wrap Babel like to automatically inject plugins and presets,
or override options. To accomplish this goal, Babel exposes several functions
that aid in loading the configuration part-way without transforming.


### loadOptions

> babel.loadOptions([options?](#options): Object)

Resolve Babel's options fully, resulting in an options object where:

* `opts.plugins` is a full list of `Plugin` instances.
* `opts.presets` is empty and all presets are flattened into `opts`.
* It can be safely passed back to Babel. Fields like [`"babelrc"`](options.md#babelrc) have been set to
  `false` so that later calls to Babel will not make a second attempt to load
  config files.

`Plugin` instances aren't meant to be manipulated directly, but often
callers will serialize this `opts` to JSON to use it as a cache key representing
the options Babel has received. Caching on this isn't 100% guaranteed to
invalidate properly, but it is the best we have at the moment.


### loadPartialConfig

> babel.loadPartialConfig([options?](#options): Object): PartialConfig

To allow systems to easily manipulate and validate a user's config, this function
resolves the plugins and presets and proceeds no further. The expectation is
that callers will take the config's `.options`, manipulate it as they see fit
and pass it back to Babel again.

* `babelrc: string | void` - The path of the [file-relative configuration](config-files.md#file-relative-configuration) file, if there was one.
* `babelignore: string | void` - The path of the `.babelignore` file, if there was one.
* `config: string | void` - The path of the [project-wide config file](config-files.md#project-wide-configuration) file, if there was one.
* `options: ValidatedOptions` - The partially resolved options, which can be manipulated and passed back to Babel again.
  * `plugins: Array<ConfigItem>` - See below.
  * `presets: Array<ConfigItem>` - See below.
  * It can be safely passed back to Babel. Options like [`"babelrc"`](options.md#babelrc) have been set
    to false so that later calls to Babel will not make a second attempt to
    load config files.
* `hasFilesystemConfig(): boolean` - Check if the resolved config loaded any settings from the filesystem.

[`ConfigItem`](#configitem-type) instances expose properties to introspect the values, but each
item should be treated as immutable. If changes are desired, the item should be
removed from the list and replaced with either a normal Babel config value, or
with a replacement item created by `babel.createConfigItem`. See that
function for information about `ConfigItem` fields.


### createConfigItem

> babel.createConfigItem(value: string | {} | Function | [string | {} | Function, {} | void], { dirname?: string, type?: "preset" | "plugin" }): ConfigItem

Allows build tooling to create and cache config items up front. If this function
is called multiple times for a given plugin, Babel will call the plugin's function itself
multiple times. If you have a clear set of expected plugins and presets to
inject, pre-constructing the config items would be recommended.


### `ConfigItem` type

Each `ConfigItem` exposes all of the information Babel knows. The fields are:

* `value: {} | Function` - The resolved value of the plugin.
* `options: {} | void` - The options object passed to the plugin.
* `dirname: string` - The path that the options are relative to.
* `name: string | void` - The name that the user gave the plugin instance, e.g. `plugins: [ ['env', {}, 'my-env'] ]`
* `file: Object | void` - Information about the plugin's file, if Babel knows it.
  * `request: string` - The file that the user requested, e.g. `"@babel/env"`
  * `resolved: string` - The full path of the resolved file, e.g. `"/tmp/node_modules/@babel/preset-env/lib/index.js"`

## DEFAULT_EXTENSIONS

> babel.DEFAULT_EXTENSIONS: ReadonlyArray<string>

A list of default extensions supported by babel (".js", ".jsx", ".es6", ".es", ".mjs").
This list is used by @babel/register and @babel/cli to determine which files need transpiling. 
Extending this list isn't possible, however @babel/cli does provide ways to support other extensions with `--extensions`.

## Options

See [the full option list here](options.md).

---

## File: docs/core-packages.md

---
title: Babel's core packages
id: core-packages
---

## Other packages

* [babel-parser](parser.md): babel-parser (Babylon) is a JavaScript parser used in Babel
* [babel-core](core.md): The core module that wraps everything in our transform api (used for integrations)
* [babel-generator](generator.md): Prints a string from an AST
* [babel-types](types.md): Babel Types is a Lodash-esque utility library for AST nodes
* [babel-register](register.md): The require hook will bind itself to node's require and automatically compile files on the fly.
* [babel-template](template.md): Generate an AST from a string template
* [babel-helpers](helpers.md): Collection of helper functions used by Babel transforms
* [babel-code-frame](code-frame.md): Generate errors that contain a code frame that point to source locations