Babel Core Tutorial

Babel Core

Babel core is the API. For v5 the babel package is the CLI and depends on babel-core. For v6, the babel-cli package is the CLI (the CLI bin command is still babel though) and the babel package doesn’t do anything. Babel-runtime I guess is just the runtime (polyfill and helpers) to support code that’s already been transformed.

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

All transformations will use your local configuration files.

Transform

babel.transform(code: string, options?: Object, callback: Function)

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

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

Example

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?: Object)

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

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

Example

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

transformAsync

babel.transformAsync(code: string, options?: Object)

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

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

Example

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

transformFile

babel.transformFile(filename: string, options?: Object, callback: Function)

Asynchronously transforms the entire contents of a file.

babel.transformFile(filename, options, callback)

Example

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

transformFileSync

babel.transformFileSync(filename: string, options?: Object)

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

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

Example

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

transformFileAsync

babel.transformFileAsync(filename: string, options?: Object)

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

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

Example

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

transformFromAst

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

Given an AST, transform it.

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?: Object)

Given an AST, transform it.

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?: Object)

Given an AST, transform it.

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?: 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?: 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?: 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?: 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” 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?: 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 then see fit and pass it back to Babel again.

  • babelrc: string | void – The path of the 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 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” 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 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”

Options

  • Primary options
  • Config Loading options
  • Plugin and Preset configuration
  • Config Merging options
  • Source Map options
  • Misc options
  • Code Generator options
  • AMD / UMD / SystemJS options
  • Option concepts

Options can be passed to Babel in a variety of ways. When passed directly to Babel, you can just pass the objects object. When Babel is used via a wrapper, it may also be necessary, or at least more useful, to pass the options via configuration files.

If passing options via @babel/cli you’ll need to kebab-case the names. i.e.

npx babel --root-mode upward file.js # equivalent of passing the rootMode config option

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
JavaScript Variables
Use Strict in JavaScript

Babel Presets

BDon’t want to set up the plugin yourself? Then no problem! You can work with Presents. Presets can operate even shareable options configurations like a set of Babel plugins .

Official Presets

We have assembled some presets for common environments:

  • @babel/preset-env
  • @babel/preset-flow
  • @babel/preset-react
  • @babel/preset-typescript

There are many other community-maintained presets available on npm !

Stage-X (Experimental Presets)

Any conversion in stage-x presets is a change to a section that is not approved for publishing as Javascript (such as ES6 / ES2015).

Adjustable change

These proposals are subject to change, so please use them with caution , especially for proposals prior to Phase 3. We plan to update the changes to stage-x presets as soon as possible after each TC39 meeting.

TC39 divides the proposal into the following phases:

  • Stage 0 – Scarecrow: Just an idea might have a related Babel plugin.
  • Stage 1 – Proposal: Worth deep.
  • Stage 2 – Draft: Initial specification.
  • Stage 3 – Candidate: Complete specification and initial browser implementation.
  • Stage 4 – End: will be added to the next annual version.

For more information, be sure to check out the latest TC39 proposal and its process documentation .

Babel Preset – ENV

@babel/preset-env is a smart preset that allows you to use the latest JavaScript without needing to micromanage which syntax transforms (and optionally, browser polyfills) are needed by your target environment(s). This both makes your life easier and JavaScript bundles smaller!

Install

With npm:

npm install --save-dev @babel/preset-env
copy

Or yarn:

yarn add @babel/preset-env --dev
copy

How Does it Work?

@babel/preset-env would not be possible if not for a number of awesome open-source projects, like browserslist, compat-table, and electron-to-chromium.

We leverage these data sources to maintain mappings of which version of our supported target environments gained support of a JavaScript syntax or browser feature, as well as a mapping of those syntaxes and features to Babel transform plugins and core-js polyfills.

It is important to note that @babel/preset-env does not support stage-x plugins.

@babel/preset-env takes any target environments you’ve specified and checks them against its mappings to compile a list of plugins and passes it to Babel.

Browserslist Integration

For browser- or Electron-based projects, we recommend using a .browserslistrc file to specify targets. You may already have this configuration file as it is used by many tools in the ecosystem, like autoprefixer, stylelint, eslint-plugin-compat and many others.

By default @babel/preset-env will use browserslist config sources unless either the targets or ignoreBrowserslistConfig options are set.

For example, to only include polyfills and code transforms needed for users whose browsers have >0.25% market share (ignoring browsers without security updates like IE 10 and BlackBerry):

Options

 {
 "presets": [
   [
     "@babel/preset-env",
     {
       "useBuiltIns": "entry"
     }
   ]
 ]
}

browserslist

 > 0.25%
not dead

or

package.json
"browserslist": "> 0.25%, not dead"

Options

For more information on setting options for a preset, refer to the preset options documentation.

targets

string | Array<string> | { [string]: string }, defaults to {}.

Describes the environments you support/target for your project.

This can either be a browserslist-compatible query:

{
 "targets": "> 0.25%, not dead"
}

Or an object of minimum environment versions to support:

{
 "targets": {
   "chrome": "58",
   "ie": "11"
 }
}

Example environments: chrome, opera, edge, firefox, safari, ie, ios, android, node, electron.

Sidenote, if no targets are specified, @babel/preset-env will transform all ECMAScript 2015+ code by default.

We don’t recommend using preset-env this way because it doesn’t take advantage of its ability to target specific browsers.

{
 "presets": ["@babel/preset-env"]
}

targets.esmodules

boolean.

You may also target browsers supporting ES Modules (https://www.ecma-international.org/ecma-262/6.0/#sec-modules). When specifying this option, the browsers field will be ignored. You can use this approach in combination with <script type=”module”></script> to conditionally serve smaller scripts to users (https://jakearchibald.com/2017/es-modules-in-browsers/#nomodule-for-backwards-compatibility).

Please note: when specifying the es modules target, browsers targets will be ignored.

{
 "presets": [
   [
     "@babel/preset-env",
     {
       "targets": {
         "esmodules": true
       }
     }
   ]
 ]
}

targets.node

string | “current” | true.

If you want to compile against the current node version, you can specify “node”: true or “node”: “current”, which would be the same as “node”: process.versions.node.

targets.safari

string | “tp”.

If you want to compile against the technology preview version of Safari, you can specify “safari”: “tp”.

targets.browsers

string | Array<string>.

A query to select browsers (ex: last 2 versions, > 5%, safari tp) using browserslist.

Note, browsers’ results are overridden by explicit items from targets.

Note: this will be removed in later version in favor of just setting “targets” to a query directly.

spec

boolean, defaults to false.

Enable more spec compliant, but potentially slower, transformations for any plugins in this preset that support them.

loose

boolean, defaults to false.

Enable “loose” transformations for any plugins in this preset that allow them.

modules

"amd" | "umd" | "systemjs" | "commonjs" | "cjs" | "auto" | false, defaults to "auto".

Enable transformation of ES6 module syntax to another module type.

Setting this to false will not transform modules.

Also note that cjs is just an alias for commonjs.

debug

boolean, defaults to false.

Outputs the targets/plugins used and the version specified in plugin data version to console.log.

include

Array<string|RegExp>, defaults to [].

An array of plugins to always include.

Valid options include any:

  • Babel plugins – both with (@babel/plugin-transform-spread) and without prefix (plugin-transform-spread) are supported.
  • Built-ins, such as es6.map, es6.set, or es6.object.assign.

Plugin names can be fully or partially specified (or using RegExp).

Acceptable inputs:

  • Full name (string): “es6.math.sign”
  • Partial name (string): “es6.math.*” (resolves to all plugins with es6.math prefix)
  • RegExp Object: /^transform-.*$/ or new RegExp(“^transform-modules-.*”)

Note that the above . is the RegExp equivalent to match any character, and not the actual ‘.’character. Also note that to match any character .* is used in RegExp as opposed to * in globformat.

This option is useful if there is a bug in a native implementation, or a combination of a non-supported feature + a supported one doesn’t work.

For example, Node 4 supports native classes but not spread. If super is used with a spread argument, then the @babel/plugin-transform-classes transform needs to be included, as it is not possible to transpile a spread with super otherwise.

NOTE: The include and exclude options only work with the plugins included with this preset; so, for example, including @babel/plugin-proposal-do-expressions or excluding @babel/plugin-proposal-function-bind will throw errors. To use a plugin not included with this preset, add them to your “plugins” directly.

exclude

Array<string|RegExp>, defaults to [].

An array of plugins to always exclude/remove.

The possible options are the same as the include option.

This option is useful for “blacklisting” a transform like @babel/plugin-transform-regenerator if you don’t use generators and don’t want to include regeneratorRuntime (when using useBuiltIns) or for using another plugin like fast-async instead of Babel’s async-to-gen.

useBuiltIns

"usage" | "entry" | false, defaults to false.

This option adds direct references to the core-js module as bare imports. Thus core-js will be resolved relative to the file itself and needs to be accessible. You may need to specify [email protected] as a top level dependency in your application if there isn’t a core-js dependency or there are multiple versions.

This option configures how @babel/preset-env handles polyfills.

useBuiltIns: ‘entry’

NOTE: Only use require(“@babel/polyfill”); once in your whole app. Multiple imports or requires of @babel/polyfill will throw an error since it can cause global collisions and other issues that are hard to trace. We recommend creating a single entry file that only contains the require statement.

This option enables a new plugin that replaces the statement import “@babel/polyfill” or require(“@babel/polyfill”) with individual requires for @babel/polyfill based on environment.npm install @babel/polyfill –save

In

import "@babel/polyfill";

Out (different based on environment)

import "core-js/modules/es7.string.pad-start";
import "core-js/modules/es7.string.pad-end";

his will also work for core-js directly (import “core-js”; or require(‘core-js’);)

useBuiltIns: ‘usage’ (experimental)

Adds specific imports for polyfills when they are used in each file. We take advantage of the fact that a bundler will load the same polyfill only once.

In 
a.js
var a = new Promise();
b.js
var b = new Map();

Out (if environment doesn’t support it)

import "core-js/modules/es6.promise";
var a = new Promise();
import "core-js/modules/es6.map";
var b = new Map();

Out (if environment doesn’t support it)

import "core-js/modules/es6.promise";
var a = new Promise();
import "core-js/modules/es6.map";
var b = new Map();

Out (if environment supports it)

var a = new Promise();
var b = new Map();

useBuiltIns: false

Don’t add polyfills automatically per file, or transform import “@babel/polyfill” to individual polyfills.

forceAllTransforms

boolean, defaults to false.

Example

NOTE: targets.uglify is deprecated and will be removed in the next major in favor of this.

By default, this preset will run all the transforms needed for the targeted environment(s). Enable this option if you want to force running all transforms, which is useful if the output will be run through UglifyJS or an environment that only supports ES5.

NOTE: Uglify has a work-in-progress “Harmony” branch to address the lack of ES6 support, but it is not yet stable. You can follow its progress in UglifyJS2 issue #448. If you require an alternative minifier which does support ES6 syntax, we recommend using babel-minify.

configPath

string, defaults to process.cwd()

The starting point where the config search for browserslist will start, and ascend to the system root until found.

ignoreBrowserslistConfig

boolean, defaults to false

Toggles whether or not browserslist config sources are used, which includes searching for any browserslist files or referencing the browserslist key inside package.json. This is useful for projects that use a browserslist config for files that won’t be compiled with Babel.

shippedProposals

boolean, defaults to false

Toggles enabling support for built-in/feature proposals that have shipped in browsers. If your target environments have native support for a feature proposal, its matching parser syntax plugin is enabled instead of performing any transform. Note that this does not enable the same transformations as @babel/preset-stage-3, since proposals can continue to change before landing in browsers.

The following are currently supported:

Builtins

Features

  • None

Babel Preset – Stage-0

As of Babel v7, all the stage presets have been deprecated. Check the blog post for more information.For upgrade instructions, see the README.

Install

npm install --save-dev @babel/preset-stage-0

Usage

Via .babelrc (Recommended)

.babelrc
{
 "presets": ["@babel/preset-stage-0"]
}

Via CLI

babel script.js --presets @babel/preset-stage-0

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-stage-0"]
});

Options

loose

boolean, defaults to false.

Enable “loose” transformations for any plugins in this preset that allow them.

useBuiltIns

boolean, defaults to false.

Will use the native built-in instead of trying to polyfill behavior for any plugins that require one.

decoratorsLegacy

boolean, defaults to false.

Use the legacy (stage 1) decorators syntax and behavior.

Babel Preset – Stage-1

As of Babel v7, all the stage presets have been deprecated.

For upgrade instructions, see the README.

The gist of Stage 1 is:

Stage 1: proposal

What is it?

A formal proposal for the feature.

What’s required?

A so-called champion must be identified who is responsible for the proposal. Either the champion or a co-champion must be a member of TC39 (source). The problem solved by the proposal must be described in prose.

The solution must be described via examples, an API and a discussion of semantics and algorithms. Lastly, potential obstacles for the proposal must be identified, such as interactions with other features and implementation challenges. Implementation-wise, polyfills and demos are needed.

What’s next?

By accepting a proposal for stage 1, TC39 declares its willingness to examine, discuss and contribute to the proposal. Going forward, major changes to the proposal are expected

Install

npm install --save-dev @babel/preset-stage-1

Usage

Via .babelrc (Recommended)

.babelrc
{
 "presets": ["@babel/preset-stage-1"]
}

Via CLI

babel script.js --presets @babel/preset-stage-1

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-stage-1"]
});

Options

loose

boolean, defaults to false.

Enable “loose” transformations for any plugins in this preset that allow them.

useBuiltIns

boolean, defaults to false.

Will use the native built-in instead of trying to polyfill behavior for any plugins that require one.

decoratorsLegacy

boolean, defaults to false.

Use the legacy (stage 1) decorators syntax and behavior.

Babel Preset – Stage-2

As of Babel v7, all the stage presets have been deprecated.

For upgrade instructions, see the README.

The gist of Stage 2 is:

Stage 2: draft

What is it?

A first version of what will be in the specification. At this point, an eventual inclusion of the feature in the standard is likely.

What’s required?

The proposal must now additionally have a formal description of the syntax and semantics of the feature (using the formal language of the ECMAScript specification).

The description should be as complete as possible, but can contain todos and placeholders. Two experimental implementations of the feature are needed, but one of them can be in a transpiler such as Babel.

What’s next?

Only incremental changes are expected from now on.

Install

npm install --save-dev @babel/preset-stage-2

Usage

Via .babelrc (Recommended)

.babelrc

{
 "presets": ["@babel/preset-stage-2"]
}

Via CLI

babel script.js --presets @babel/preset-stage-2

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-stage-2"]
});

Options

loose

boolean, defaults to false.

Enable “loose” transformations for any plugins in this preset that allow them.

useBuiltIns

boolean, defaults to false.

Will use the native built-in instead of trying to polyfill behavior for any plugins that require one.

decoratorsLegacy

boolean, defaults to false.

Use the legacy (stage 1) decorators syntax and behavior.

Babel Preset – Stage-3

As of Babel v7, all the stage presets have been deprecated.

For upgrade instructions, see the README.

The gist of Stage 3 is:

Stage 3: candidate

What is it?

The proposal is mostly finished and now needs feedback from implementations and users to progress further.

What’s required?

The spec text must be complete. Designated reviewers (appointed by TC39, not by the champion) and the ECMAScript spec editor must sign off on the spec text. There must be at least two spec-compliant implementations (which don’t have to be enabled by default).

What’s next?

Henceforth, changes should only be made in response to critical issues raised by the implementations and their use.

Install

npm install --save-dev @babel/preset-stage-3

Usage

Via .babelrc (Recommended)

.babelrc

{
 "presets": ["@babel/preset-stage-3"]
}

Via CLI

babel script.js --presets @babel/preset-stage-3

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-stage-3"]
});

Options

loose

boolean, defaults to false.

Enable “loose” transformations for any plugins in this preset that allow them.

useBuiltIns

boolean, defaults to false.

Will use the native built-in instead of trying to polyfill behavior for any plugins that require one.

Babel Preset – Flow

This preset includes the following plugins:

  • @babel/plugin-transform-flow-strip-types

Example

In

function foo(one: any, two: number, three?): string {}
Copy

Out

function foo(one, two, three) {}

Installation

npm install --save-dev @babel/preset-flow

Usage

Via .babelrc (Recommended)

.babelrc

{
 "presets": ["@babel/preset-flow"]
}

Via CLI

babel --presets @babel/preset-flow script.js

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-flow"],
});

Babel Preset – React

This preset always includes the following plugins:

  • @babel/plugin-syntax-jsx
  • @babel/plugin-transform-react-jsx
  • @babel/plugin-transform-react-display-name

And with the development option:

  • @babel/plugin-transform-react-jsx-self
  • @babel/plugin-transform-react-jsx-source

Note: Flow syntax support is no longer enabled in v7. For that, you will need to add the Flow preset.

Installation

You can also check out the React Getting Started page

npm install --save-dev @babel/preset-react

Usage

Via .babelrc (Recommended)

.babelrc

Without options:

{
 "presets": ["@babel/preset-react"]
}

With options:

{
 "presets": [
   [
     "@babel/preset-react",
     {
       "pragma": "dom", // default pragma is React.createElement
       "pragmaFrag": "DomFrag", // default is React.Fragment
       "throwIfNamespace": false // defaults to true
     }
   ]
 ]
}

Via CLI

babel --presets @babel/preset-react script.js

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-react"],
});

Options

pragma

string, defaults to React.createElement.

Replace the function used when compiling JSX expressions.

pragmaFrag

string, defaults to React.Fragment.

Replace the component used when compiling JSX fragments.

useBuiltIns

boolean, defaults to false.

Will use the native built-in instead of trying to polyfill behavior for any plugins that require one.

development

boolean, defaults to false.

Toggles plugins that aid in development, such as @babel/plugin-transform-react-jsx-self and @babel/plugin-transform-react-jsx-source.

This is useful when combined with the env option configuration or js config files.

throwIfNamespace

boolean, defaults to true.

Toggles whether or not to throw an error if a XML namespaced tag name is used. For example:

<f:image />

Though the JSX spec allows this, it is disabled by default since React’s JSX does not currently have support for it.

.babelrc.js

module.exports = {
 presets: [
   [
     "@babel/preset-react",
     {
       development: process.env.BABEL_ENV === "development",
     },
   ],
 ],
};

.babelrc

Note: the env option will likely get deprecated soon

{
 "presets": ["@babel/preset-react"],
 "env": {
   "development": {
     "presets": [["@babel/preset-react", { "development": true }]]
   }
 }
}

Babel Preset – Minify

  • Install
  • Usage
  • Options

Install

npm install babel-preset-minify --save-dev

Usage

Via .babelrc (Recommended)

.babelrc

{
 "presets": ["minify"]
}

or pass in options –

{
 "presets": [["minify", {
   "mangle": {
     "exclude": ["MyCustomError"]
   },
   "unsafe": {
     "typeConstructors": false
   },
   "keepFnName": true
 }]]
}

Via CLI

babel script.js --presets minify

Via Node API

require("@babel/core").transform("code", {
 presets: ["minify"]
});

Options

Two types of options:

  1. 1-1 mapping with plugin
  2. The same option passed to multiple plugins

1-1 mapping with plugin

  • false – disable plugin
  • true – enable plugin
  • { …pluginOpts } – enable plugin and pass pluginOpts to plugin

Examples

{
 "presets": [["minify", {
   "evaluate": false,
   "mangle": true
 }]]
}
{
 "presets": [["minify", {
   "mangle": {
     "exclude": ["ParserError", "NetworkError"]
   }
 }]]
}
{
 "presets": [["minify", {
   "keepFnName": true
 }]]
}
// is the same as
{
 "presets": [["minify", {
   "mangle": {
     "keepFnName": true
   },
   "deadcode": {
     "keepFnName": true
   }
 }]]
}

Babel Preset – Typescript

This preset includes the following plugins:

  • @babel/plugin-transform-typescript

You will need to specify –extensions “.ts” for @babel/cli & @babel/node cli’s to handle .ts files.

Example

In

const x: number = 0

Out

const x = 0;

Installation

npm install --save-dev @babel/preset-typescript

Usage

Via .babelrc (Recommended)

.babelrc

{
 "presets": ["@babel/preset-typescript"]
}

Via CLI

babel --presets @babel/preset-typescript script.ts

Via Node API

require("@babel/core").transform("code", {
 presets: ["@babel/preset-typescript"],
});

Options

isTSX

boolean, defaults to false.

Forcibly enables jsx parsing. Otherwise angle brackets will be treated as typescript’s legacy type assertion var foo = <string>bar;. Also, isTSX: true requires allExtensions: true

jsxPragma

string, defaults to React.

Replace the function used when compiling JSX expressions.

This is so that we know that the import is not a type import, and should not be removed

allExtensions

boolean, defaults to false.

Indicates that every file should be parsed as TS or TSX (depending on the isTSX option)

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
Use Strict in JavaScript
JavaScript Variables


Babel CLI & Babel Polyfill Tutorial

Babel 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:

npm install --save-dev @babel/core @babel/cli
Copy

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:

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

Usage

babel script.js

Note: These instructions use the excellent npx command to run the locally installed executables. You can drop it inside of an npm 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.

npx babel script.js
# output...

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

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: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.

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

npx babel src --out-dir lib

Compile the entire src directory and output it as a single concatenated file.npx babel src –out-file script-compiled.js

Ignore files

Ignore spec and test files

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

Copy files

Copy files that will not be compilednpx babel src –out-dir lib –copy-files

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

Piping Files

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

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

Using Plugins

Use the –plugins option to specify plugins to use in compilation

npx babel script.js --out-file script-compiled.js [email protected]/proposal-class-properties,@babel/transform-modules-amd

Using Presets

Use the –presets option to specify plugins to use in compilation

npx babel script.js --out-file script-compiled.js [email protected]/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

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

Advanced Usage

There are many more options available, babel –help and other sections for more information.

Babel Polyfill

Babel includes a polyfill that includes a custom regenerator runtime and core-js.

This will emulate a full ES2015+ environment (no < Stage 4 proposals) and is intended to be used in an application rather than a library/tool. (this polyfill is automatically loaded when using babel-node).

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). The polyfill adds to the global scope as well as native prototypes like String in order to do this.

Installation

npm install --save @babel/polyfill
copy

Because this is a polyfill (which will run before your source code), we need it to be a dependency, not a devDependency

Size

The polyfill is provided as a convenience but you should use it with @babel/preset-env and the useBuiltIns option so that it doesn’t include the whole polyfill which isn’t always needed. Otherwise, we would recommend you import the individual polyfills manually.

TC39 Proposals

If you need to use a proposal that is not Stage 4, @babel/polyfill will not automatically import those for you. You will have to import those from another polyfill like core-js individually. We may work towards including this as separate files in @babel/polyfill soon.

Usage in Node / Browserify / Webpack

To include the polyfill you need to require it at the top of the entry point to your application.

Make sure it is called before all other code/require statements!

 require("@babel/polyfill");

If you are using ES6’s import syntax in your application’s entry point, you should instead import the polyfill at the top of the entry point to ensure the polyfills are loaded first:

import "@babel/polyfill";

With webpack, there are multiple ways to include the polyfills:

  • When used alongside @babel/preset-env,
    • If useBuiltIns: ‘usage’ is specified in .babelrc then do not include @babel/polyfill in either webpack.config.js entry array nor source. Note, @babel/polyfill still needs to be installed.
    • If useBuiltIns: ‘entry’ is specified in .babelrc then include @babel/polyfill at the top of the entry point to your application via require or import as discussed above.
    • If useBuiltIns key is not specified or it is explicitly set with useBuiltIns: false in your .babelrc, add @babel/polyfill directly to the entry array in your webpack.config.js.
module.exports = {
 entry: ["@babel/polyfill", "./app/js"],
};
  • If @babel/preset-env is not used then add @babel/polyfill to webpack entry array as discussed above. It can still be added at the top of the entry point to application via import or require, but this is not recommended.

We do not recommend that you import the whole polyfill directly: either try the useBuiltInsoptions or import only the polyfills you need manually (either from this package or somewhere else).

Usage in Browser

Available from the dist/polyfill.js file within a @babel/polyfill npm release. This needs to be included before all your compiled Babel code. You can either prepend it to your compiled code or include it in a <script> before it.

NOTE: Do not require this via browserify etc, use @babel/polyfill.

Details

If you are looking for something that won’t modify globals to be used in a tool/library, checkout the transform-runtime plugin. This means you won’t be able to use the instance methods mentioned above like Array.prototype.includes.

Note: Depending on what ES2015 methods you actually use, you may not need to use @babel/polyfill or the runtime plugin. You may want to only load the specific polyfills you are using(like Object.assign) or just document that the environment the library is being loaded in should include certain polyfills.

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
JavaScript Variables
Use Strict in JavaScript

Babel Tutorial For Beginners 2019

What is Babel?

Babel Tutorial from Coding compiler. Babel or Babel.js is a free and open-source JavaScript compiler and configurable transpiler used in web development. Let’s start learning Babel with code examples.

Babel is a JavaScript compiler

Babel is a toolchain that is used to convert ECMAScript 2015+ code into a backward compatible version of JavaScript code in an older browser or environment:

  • Conversion syntax
  • Polyfill implements missing features in the target environment (via @babel/polyfill )
  • Source code conversion (codemods)
 // Babel Input: ES2015 arrow function
[1, 2, 3].map((n) => n + 1);

// Babel Output: ES5 equivalent
[1, 2, 3].map(function(n) {
 return n + 1;
});

For a great tutorial on compilers, check out the Super Micro Compiler, which explains how Babel itself works in high-level languages.

ES2015 and others

Babel supports the latest version of JavaScript through a syntax converter.

These plugins allow you to use the new syntax now without waiting for browser support. Check out our usage guide to get started.

JSX and React

Babel can convert JSX syntax! Check out the React preset to get started. And babel-sublime use with syntax highlighting can be elevated to a whole new level.

You can install the preset by the following command

npm install --save-dev @babel/preset-react

And @babel/preset-react added to your Babel configuration.

 export default React.createClass({
 getInitialState() {
   return { num: this.getRandomNumber() };
 },

 getRandomNumber() {
   return Math.ceil(Math.random() * 6);
 },

 render() {
   return <div>
     Your dice roll:
     {this.state.num}
   </div>;
 }
});

Learn more about JSX .

Type annotations (Flow and TypeScript)

Babel can delete type annotations! Check the Flow preset or TypeScript preset to get started. Note that Babel does not perform type checking ; you can still install Flow or TypeScript for type checking.

You can install the flow preset by using this command.

npm install --save-dev @babel/preset-flow
// @flow
function square(n: number): number {
 return n * n;
}

You can also install the typescript preset with this command.

npm install --save-dev @babel/preset-typescript

function Greeter(greeting: string) {
   this.greeting = greeting;
}

Learn more about Flow and TypeScript .

Pluggable

Babel is built with plugins. You can use your existing plugins to write your own conversion pipeline or write your own plugins. Easily use a set of plugins by using or creating a preset .

Use astexplorer.net to dynamically create plugins or use generator-babel-plugin to generate plugin templates.

// A plugin is just a function
export default function ({types: t}) {
 return {
   visitor: {
     Identifier(path) {
       let name = path.node.name; // reverse the name: JavaScript -> tpircSavaJ
       path.node.name = name.split('').reverse().join('');
     }
   }
 };
}

Debuggable

Source map is supported , so you can easily debug compiled code.

Normative

Babel tries to follow the ECMAScript standard as much as possible. In order to balance performance, it may also have specific options to make it more compliant.

Compressibility

Babel tries to use as little code as possible without relying on a large runtime environment.

Some situations can be difficult to achieve, so to ensure readability, file size, and (running) speed, some compliance is sacrificed for a particular conversion, providing the “loose” option.

Babel Usage

There are many tools in the Babel toolchain that make it easy to use Babel, whether you are an “end user” or a Babel in your build. This article is a quick guide to using these tools, and you can read more about them in the Usage section of the documentation.

If you are using a framework, the way different frameworks configure Babel may be different, and in fact some frameworks are already configured for you. Please refer to the interactive setup guide for the specific configuration method .

Overview

This article will show you how to compile JavaScript code that uses the ES2015+ syntax into code for the current browser. This will involve converting the new grammar and implementing missing features.

The entire configuration process includes:

Use the following command to install packages:

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

Create a file named in the root directory of the project using the following babel.config.js profile:

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

> The browser list above is just an example of display purpose. You must adjust to the browser you want to support.

This command will run all the code from the src catalog compiled to lib:

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

Copy

You can [email protected] npm package that comes with runner, with a npx babel replacement ./node_modules/.bin/babel to shorten the command.

Read on to get a step-by-step description of how it works and an introduction to each tool you use.

Basic usage of the CLI

All of the Babel modules you need will be released as a separate npm package, with a range @babel (starting with version 7). This modular design allows each tool to be designed for a specific use case. Let us look at @babel/core and @babel/cli.

Core library

The core functionality of Babel is in the @babel/core module. Install by the following command:

npm install --save-dev @babel/core

You can directly in JavaScript require it and so use it as follows:

const babel = require("@babel/core");
babel.transform("code", optionsObject);

As an end user, you may want to install other tools as @babel/corean interface, and can be well integrated in your development process. Even so, you may still need to check its documentation page for these options, most of which can be set by other tools.

CLI tool

@babel/cli is a tool that allows you to use babel from your terminal. The following are examples of installation commands and basic usage:

npm install --save-dev @babel/core @babel/cli
./node_modules/.bin/babel src --out-dir lib

It uses analytical methods we set up to resolve src all of the JavaScript files in a directory, and the output of each converted file to lib the directory. Since we haven’t set up parsing yet, the output code here will be the same as the input (the exact code style is not preserved). We can specify the way we want to parse by passing them as options.

We use the above –out-dir options. You can use –help it to view the remaining options cli tool accepts operation. But for us the most important thing is –plugins, and –presets.

Plugins & Presets

The code conversion comes in the form of a plugin, which is a small JavaScript program that tells Babel how to convert the code. You can even write your own plugin to apply whatever code conversion you want. To convert the ES2015+ syntax to ES5, we can rely on official plugins such as @babel/plugin-transform-arrow-functions:

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

./node_modules/.bin/babel src --out-dir lib [email protected]/plugin-transform-arrow-functions

Now all the arrow functions in our code will be converted to ES5 compatible function expressions:

const fn = () => 1;
// converted to
var fn = function fn() {
 return 1;
};

This is a good beginning! If you want to convert the code there are other ES2015+ features. Instead of adding all the plugins we want, we can use “preset” instead of a pre-set set of plugins.

Just like using plugins, you can also create your own presets and share any plugin combinations you need. In this example, we used env preset.

 npm install --save-dev @babel/preset-env
./node_modules/.bin/babel src --out-dir lib [email protected]/env

Without any configuration, this preset includes all plugins that support modern JavaScript (ES2015, ES2016, etc.). But presets can also be chosen. Instead of passing in the cli and preset options from the terminal, we pass another way of passing in the options: the configuration file.

Configuration

There are several different ways to configure the file, depending on your needs. Be sure to read about how to configure Babel in-depth guide for more information.

Now, let’s create a named babel.config.js file, which contains the following:

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

module.exports = { presets };

Env Preset now only loads the conversion plugin for features not available in the target browser. Next we look at polyfills.

Polyfill

The @babel/polyfill module includes core-js and a custom regenerator runtime to simulate the full ES2015+ environment.

This means that you can use like Promise or WeakMap such new built-in functions, like Array.from or Object.assign such static methods as Array.prototype.includes instance methods such, as well as generator function (provided you use the regenerator plug-in). To do this, polyfill increase the global scope as well as String Native prototype like this.

For the author of the library/tool, it is too redundant. If you do not like Array.prototype.includes such an instance method, you can use the transform runtime plugin instead of global pollution @babel/polyfill.

Further, if you know exactly what you need to implement, you can get them directly from core-js .

Since we are building an app, we can just install @babel/polyfill:

npm install --save @babel/polyfill

Note that –save option instead –save-dev, because this is a polyfill run before the source code needed.

Fortunately for us, we are using a env preset, which has an “useBuiltIns” option, when set “usage”when, in fact, the last application optimization mentioned above, you need only include polyfill. With this new option, the configuration changes are as follows:

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

module.exports = { presets };

Babel will check all of your code to find missing features in the target environment and only include the polyfills you need. For example this code:

Promise.resolve().finally();

Will become this (because Edge 17 does not Promise.prototype.finally):

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

If we do not env preset the “useBuiltIns” setting options for “usage”, it is necessary to require the code before the other one full of polyfill.

Summery:

We used @babel/cli to run from the terminal Babel, @babel/polyfill to implement all new JavaScript function, env PRESET only contains the conversion functions we use to achieve our goals browser missing features.

Configuring Babel

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

All Babel API options are allowed. However, if the option requires JavaScript, you may want to use a Javascript configuration file.

What’s your use case?

  • You want to programmatically create the configuration?
  • You want to compile node_modules?
babel.config.js is for you!
  • You have a static configuration that only applies to your simple single package?
.babelrc is for you!
  • The Guy Fieri is your hero?

We recommend to use the babel.config.js format. Babel itself is using it.

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

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

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

 return {
   presets,
   plugins
 };
}

Check out the babel.config.js documentation to see more configuration options.

.babelrc

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

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

Check out the .babelrc documentation to see more configuration options.

package.json

Alternatively, you can choose to specify your .babelrc config from within package.json using the babel key like so:

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

.babelrc.js

The configuration is the same as .babelrc, but you can write it using JavaScript.

 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:

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

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

module.exports = { presets, plugins };

Using the CLI (@babel/cli)

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

Check out the babel-cli documentation to see more configuration options.

Using the API (@babel/core)

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

Babel Code Editors – IDE For Babel

Syntax highlighting

Many popular editors now support ES2015+ syntax highlighting directly, while others require additional extensions. This guide will help you support syntax highlighting.

If you want more advanced integration, you can check out the installation guide.

Hint: The font used in the screenshot above is FiraCode .

Atom

Install the language-babel component and follow the instructions .

Sublime Text 3

First, install Package Control . Then install the Babel components from the Package Control menu and follow the instructions .

Vim

Install the vim-javascript plugin, which provides improved syntax highlighting and JavaScript indentation support for Vim.

Another approach is and es.next.syntax used together yajs.vim .

Visual Studio Code

Install the sublime-babel-vscode extension and follow the instructions.

There are other ways to support syntax highlighting, and you can learn more in the Visual Studio Code documentation .

WebStorm

WebStorm now supports ES2015+ without installing any additional extensions. However, you may need to enable him .

Plugins

Babel is a compiler (source code => output code). Like many other compilers it runs in 3 stages: parsing, transforming, and printing.

Now, out of the box Babel doesn’t do anything. It basically acts like const babel = code => code; by parsing the code and then generating the same code back out again. You will need to add plugins for Babel to do anything.

Instead of individual plugins, you can also enable a set of plugins in a preset.

Transform Plugins

These plugins apply transformations to your code.

Transform plugins will enable the corresponding syntax plugin so you don’t have to specify both.

ES3

  • member-expression-literals
  • property-literals
  • reserved-words

ES5

  • property-mutators

ES2015

  • arrow-functions
  • block-scoped-functions
  • block-scoping
  • classes
  • computed-properties
  • destructuring
  • duplicate-keys
  • for-of
  • function-name
  • instanceof
  • literals
  • new-target
  • object-super
  • parameters
  • shorthand-properties
  • spread
  • sticky-regex
  • template-literals
  • typeof-symbol
  • unicode-regex

ES2016

  • exponentiation-operator

ES2017

  • async-to-generator

ES2018

  • async-generator-functions
  • dotall-regex
  • named-capturing-groups-regex
  • object-rest-spread
  • optional-catch-binding
  • unicode-property-regex

Modules

  • modules-amd
  • modules-commonjs
  • modules-systemjs
  • modules-umd

Experimental

  • class-properties
  • decorators
  • do-expressions
  • export-default-from
  • export-namespace-from
  • function-bind
  • function-sent
  • logical-assignment-operators
  • nullish-coalescing-operator
  • numeric-separator
  • optional-chaining
  • pipeline-operator
  • throw-expressions

Minification

Check out our minifier based on Babel!

These plugins are in the minify repo.

  • inline-consecutive-adds
  • inline-environment-variables
  • member-expression-literals
  • merge-sibling-variables
  • minify-booleans
  • minify-builtins
  • minify-constant-folding
  • minify-dead-code-elimination
  • minify-flip-comparisons
  • minify-guarded-expressions
  • minify-infinity
  • minify-mangle-names
  • minify-numeric-literals
  • minify-replace
  • minify-simplify
  • minify-type-constructors
  • node-env-inline
  • property-literals
  • regexp-constructors
  • remove-console
  • remove-debugger
  • remove-undefined
  • simplify-comparison-operators
  • undefined-to-void

React

  • react-constant-elements
  • react-display-name
  • react-inline-elements
  • react-jsx
  • react-jsx-compat
  • react-jsx-self
  • react-jsx-source

Other

  • external-helpers
  • flow-strip-types
  • jscript
  • object-assign
  • object-set-prototype-of-to-assign
  • proto-to-assign
  • regenerator
  • runtime
  • strict-mode
  • typescript

Syntax Plugins

These plugins only allow Babel to parse specific types of syntax (not transform).

NOTE: transform plugins automatically enable the syntax plugins. So you don’t need to specify the syntax plugin if the corresponding transform plugin is used already.

Alternatively, you can also provide any plugins option from the Babel parser:

Your .babelrc:

{
 "parserOpts": {
   "plugins": ["jsx", "flow"]
 }
}

Plugin/Preset Paths

If the plugin is on npm, you can pass in the name of the plugin and babel will check that it’s installed in node_modules

{
 "plugins": ["babel-plugin-myPlugin"]
}

You can also specify an relative/absolute path to your plugin.

{
 "plugins": ["./node_modules/asdf/plugin"]
}

Plugin Shorthand

If the name of the package is prefixed with babel-plugin-, you can use a shorthand:

{
 "plugins": [
   "myPlugin",
   "babel-plugin-myPlugin" // equivalent
 ]
}

This also works with scoped packages:

{
"plugins": [
   "@org/babel-plugin-name",
   "@org/name" // equivalent
 ]
}

Plugin Ordering

Ordering matters for each visitor in the plugin.

This means if two transforms both visit the “Program” node, the transforms will run in either plugin or preset order.

  • Plugins run before Presets.
  • Plugin ordering is first to last.
  • Preset ordering is reversed (last to first).

For example:

 {
 "plugins": ["transform-decorators-legacy", "transform-class-properties"]
}

Will run transform-decorators-legacy then transform-class-properties.

It is important to remember that with presets, the order is reversed. The following:

{
 "presets": ["es2015", "react", "stage-2"]
}

Will run in the following order: stage-2, react, then es2015.

This is mostly for ensuring backwards compatibility, since most users list “es2015” before “stage-0”. For more information, see notes on potential traversal API changes.

Plugin Options

Both plugins and presets can have options specified by wrapping the name and an options object in an array inside your config.

For specifying no options, these are all equivalent:

 {
 "
plugins": ["pluginA", ["pluginA"], ["pluginA", {}]]
}

To specify an option, pass an object with the keys as the option names.

 {
 "plugins": [
   [
     "transform-async-to-module-method",
     {
       "module": "bluebird",
       "method": "coroutine"
     }
   ]
 ]
}

Settings options for presets works exactly the same:

 {
 "presets": [
   [
     "env",
     {
       "loose": true,
       "modules": false
     }
   ]
 ]
}

Plugin Development

Please refer to the excellent babel-handbook to learn how to create your own plugins.

The simple plugin that reverses names (from the homepage):

 export default function() {
 return {
   visitor: {
     Identifier(path) {
       const name = path.node.name;
       // reverse the name: JavaScript -> tpircSavaJ
       path.node.name = name
         .split("")
         .reverse()
         .join("");
     },
   },
 };
}

Presets

Don’t want to set up the plugin yourself? no problem! Presets can operate even shareable options configurations like a set of Babel plugins .

Official Presets

We have assembled some presets for common environments:

  • @babel/preset-env
  • @babel/preset-flow
  • @babel/preset-react
  • @babel/preset-typescript

There are many other community-maintained presets available on npm !

Stage-X (Experimental Presets)

Any conversion in stage-x presets is a change to a section that is not approved for publishing as Javascript (such as ES6 / ES2015).

Adjustable change

These proposals are subject to change, so please use them with caution , especially for proposals prior to Phase 3. We plan to update the changes to stage-x presets as soon as possible after each TC39 meeting.

TC39 divides the proposal into the following phases:

  • Stage 0 – Scarecrow: Just an idea might have a related Babel plugin.
  • Stage 1 – Proposal: Worth deep.
  • Stage 2 – Draft: Initial specification.
  • Stage 3 – Candidate: Complete specification and initial browser implementation.
  • Stage 4 – End: will be added to the next annual version.

For more information, be sure to check out the latest TC39 proposal and its process documentation .

Yehuda Katz (@wycatz) explains the TC39 phase process in several articles in thefeedbackloop.xyz : Stage 0 and 1 , Stage 2 , Stage 3 .

Create Preset

You only need to export a configuration to create your own preset.

It just returns an array of plugins just…

module.exports = function() {
 return {
   plugins: [
     "pluginA",
     "pluginB",
     "pluginC",
   ]
 };
}

Presets can contain other presets and plugins with options.

 module.exports = () => ({
 presets: [
   require("@babel/preset-env"),
 ],
 plugins: [
   [require("@babel/plugin-proposal-class-properties"), { loose: true }],
   require("@babel/plugin-proposal-object-rest-spread"),
 ],
});

See the babel handbook section for more information .

Preset path

If the preset on npm, you can pass the default name, babel will check if it has been installed node_modulesin

{
 "presets": ["babel-preset-myPreset"]
}

You can also specify the relative/absolute path of presets.

{
 "presets": ["./myProject/myPreset"]
}

Preset shorthand

If the name of the package to babel-preset-as a prefix, you can use the shorthand:

{
 "presets": [
   "myPreset",
   "babel-preset-myPreset" // Equivalent
 ]
}

This also applies to the scoped package:

 {
 "presets": [
   "@org/babel-preset-name",
   "@org/name" // Equivalent
 ]
}

Preset order

The order of Preset is the opposite (from the last to the first).

 {
 "presets": [
   "a",
   "b",
   "c"
 ]
}

Will run in the following order: c, b, then a.

This is mainly to ensure backward compatibility, as most users list “es2015” before “stage-0”.

Preset option

Both plugins and presets can specify options by placing name and option objects in an array in the configuration.

These are equivalent for not specifying options:

 {
 "presets": [
   "presetA",
   ["presetA"],
   ["presetA", {}],
 ]
}

To specify an option, pass the option name as the key pass object.

{
 "presets": [
   ["@babel/preset-env", {
     "loose": true,
     "modules": false
   }]
 ]
}

Babel Usage Options

  • Primary options
  • Config Loading options
  • Plugin and Preset configuration
  • Config Merging options
  • Source Map options
  • Misc options
  • Code Generator options
  • AMD / UMD / SystemJS options
  • Option concepts

Options can be passed to Babel in a variety of ways. When passed directly to Babel, you can just pass the objects object. When Babel is used via a wrapper, it may also be necessary, or at least more useful, to pass the options via configuration files.

If passing options via @babel/cli you’ll need to kebab-case the names. i.e.

npx babel --root-mode upward file.js # equivalent of passing the rootMode config option

Copy

Primary options

These options are only allowed as part of Babel’s programmatic options, so they are primarily for use by tools that wrap around Babel, or people calling babel.transform directly. Users of Babel’s integrations, like babel-loader or @babel/register are unlikely to use these.

cwd

Type: string

Default: process.cwd()

The working directory that all paths in the programmatic options will be resolved relative to.

caller

Type: Object with a string-typed “name” property.

Utilities may pass a caller object to identify themselves to Babel and pass capability-related flags for use by configs, presets and plugins. For example

 babel.transformFileSync("example.js", {
 caller: {
   name: "my-custom-tool",
   supportsStaticESM: true
 },
})

would allow plugins and presets to decide that, since ES modules are supported, they will skip compilation of ES modules into CommonJS modules.

filename

Type: string

The filename associated with the code currently being compiled, if there is one. The filename is optional, but not all of Babel’s functionality is available when the filename is unknown, because a subset of options rely on the filename for their functionality.

The three primary cases users could run into are:

  • The filename is exposed to plugins. Some plugins may require the presence of the filename.
  • Options like “test”, “exclude”, and “ignore” require the filename for string/RegExp matching.
  • .babelrc files are loaded relative to the file being compiled. If this option is omitted, Babel will behave as if babelrc: false has been set.

filenameRelative

Type: string

Default: path.relative(opts.cwd, opts.filename) (if “filename” was passed)

Used as the default value for Babel’s sourceFileName option, and used as part of generation of filenames for the AMD / UMD / SystemJS module transforms.

code

Type: boolean

Default: true

Babel’s default return value includes code and map properties with the resulting generated code. In some contexts where multiple calls to Babel are being made, it can be helpful to disable code generation and instead use ast: true to get the AST directly in order to avoid doing unnecessary work.

ast

Type: boolean

Default: false

Babel’s default is to generate a string and a sourcemap, but in some contexts it can be useful to get the AST itself. The primary use case for this would be a chain of multiple transform passes, along the lines of

const filename = "example.js";
const source = fs.readFileSync(filename, "utf8");

// Load and compile file normally, but skip code generation.
const { ast } = babel.transformSync(source, { filename, ast: true, code: false });

// Minify the file in a second pass and generate the output code here.
const { code, map } = babel.transformFromAstSync(ast, source, {
 filename,
 presets: ["minify"],
 babelrc: false,
 configFile: false,
});

Note: This option is not on by default because the majority of users won’t need it and because we’d like to eventually add a caching layer to Babel. Having to cache the AST structure will take significantly more space.

Config Loading options

Loading configuration can get a little complex as environments can have several types of configuration files, and those configuration files can have various nested configuration objects that apply depending on the configuration.

root

Type: string

Default: opts.cwd

Placement: Only allowed in Babel’s programmatic options

The initial path that will be processed based on the “rootMode” to determine the conceptual root folder for the current Babel project. This is used in two primary cases:

  • The base directory when checking for the default “configFile” value
  • The default value for “babelrcRoots”.

rootMode

Type: “root” | “upward” | “upward-optional”

Default: “root”

Placement: Only allowed in Babel’s programmatic options

Version: ^7.1.0

This option, combined with the “root” value, defines how Babel chooses its project root. The different modes define different ways that Babel can process the “root” value to get the final project root.

  • “root” – Passes the “root” value through as unchanged.
  • “upward” – Walks upward from the “root” directory, looking for a directory containing a babel.config.js file, and throws an error if a babel.config.js is not found.
  • “upward-optional” – Walk upward from the “root” directory, looking for a directory containing a babel.config.js file, and falls back to “root” if a babel.config.js is not found.

“root” is the default mode because it avoids the risk that Babel will accidentally load a babel.config.js that is entirely outside of the current project folder. If you use “upward-optional”, be aware that it will walk up the directory structure all the way to the filesystem root, and it is always possible that someone will have a forgotten babel.config.js in their home directory, which could cause unexpected errors in your builds.

Users with monorepo project structures that run builds/tests on a per-package basis may well want to use “upward” since monorepos often have a babel.config.js in the project root. Running Babel in a monorepo subdirectory without “upward”, will cause Babel to skip loading any babel.config.js files in the project root, which can lead to unexpected errors and compilation failure.

envName

Type: string

Default: process.env.BABEL_ENV || process.env.NODE_ENV || “development”

Placement: Only allowed in Babel’s programmatic options

The current active environment used during configuration loading. This value is used as the key when resolving “env” configs, and is also available inside configuration functions, plugins, and presets, via the api.env() function.

configFile

Type: string | boolean

Default: path.resolve(opts.root, “babel.config.js”), if it exists, false otherwise

Placement: Only allowed in Babel’s programmatic options

Defaults to searching for a default babel.config.js file, but can be passed the path of any JS or JSON5 config file.

NOTE: This option does not affect loading of .babelrc files, so while it may be tempting to do configFile: “./foo/.babelrc”, it is not recommended. If the given .babelrc is loaded via the standard file-relative logic, you’ll end up loading the same config file twice, merging it with itself. If you are linking a specific config file, it is recommended to stick with a naming scheme that is independent of the “babelrc” name.

babelrc

Type: boolean

Default: true as long as the filename option has been specified

Placement: Allowed in Babel’s programmatic options, or inside of the loaded “configFile”. A programmatic option will override a config file one.

true will enable searching for configuration files relative to the “filename” provided to Babel.

A babelrc value passed in the programmatic options will override one set within a configuration file.

Note: .babelrc files are only loaded if the current “filename” is inside of a package that matches one of the “babelrcRoots” packages.

babelrcRoots

Type: boolean | MatchPattern | Array<MatchPattern>

Default: opts.root

Placement: Allowed in Babel’s programmatic options, or inside of the loaded config File. A programmatic option will override a config file one.

By default, Babel will only search for .babelrc files within the “root” package because otherwise Babel cannot know if a given .babelrc is meant to be loaded, or if it’s “plugins” and “presets”have even been installed, since the file being compiled could be inside node_modules, or have been symlinked into the project.

This option allows users to provide a list of other packages that should be considered “root” packages when considering whether to load .babelrc files.

For example, a monorepo setup that wishes to allow individual packages to have their own configs might want to do

 babelrcRoots: [
 // Keep the root as a root
 ".",

 // Also consider monorepo packages "root" and load their .babelrc files.
 "./packages/*"
]

Plugin and Preset options

plugins

Type: Array<PluginEntry | Plugin> (PluginEntry)

Default: []

An array of plugins to activate when processing this file. For more information on how individual entries interact, especially when used across multiple nested “env” and “overrides” configs, see merging.

Note: The option also allows Plugin instances from Babel itself, but using these directly is not recommended. If you need to create a persistent representation of a plugin or preset, you should use babel.createConfigItem().

presets

Type: Array<PresetEntry> (PresetEntry)

Default: []

An array of presets to activate when processing this file. For more information on how individual entries interact, especially when used across multiple nested “env” and “overrides” configs, see merging.

Note: The format of presets is identical to plugins, except for the fact that name normalization expects “preset-” instead of “plugin-“, and presets cannot be instances of Plugin.

passPerPreset

Type: boolean

Default: false

Status: Deprecated

Instructs Babel to run each of the presets in the presets array as an independent pass. This option tends to introduce a lot of confusion around the exact ordering of plugins, but can be useful if you absolutely need to run a set of operations as independent compilation passes.

Note: This option may be removed in future Babel versions as we add better support for defining ordering between plugins.

Config Merging options

extends

Type: string

Placement: Not allowed inside of presets

Configs may “extend” other configuration files. Config fields in the current config will be merged on top of the extended file’s configuration.

env

Type: { [envKey: string]: Options }

Placement: May not be nested inside of another env block.

Allows for entire nested configuration options that will only be enabled if the envKey matches the envName option.

Note: env[envKey] options will be merged on top of the options specified in the root object.

overrides

Type: Array<Options>

Placement: May not be nested inside of another overrides object, or within an env block.

Allows users to provide an array of options that will be merged into the current configuration one at a time. This feature is best used alongside the “test”/”include”/”exclude” options to provide conditions for which an override should apply. For example:

overrides: [{
 test: "./vendor/large.min.js",
 compact: true,
}],
Copy

could be used to enable the compact option for one specific file that is known to be large and minified, and tell Babel not to bother trying to print the file nicely.

test

Type: MatchPattern | Array<MatchPattern> (MatchPattern)

If all patterns fail to match, the current configuration object is considered inactive and is ignored during config processing. This option is most useful when used within an overrides option object, but it’s allowed anywhere.

Note: These toggles do not affect the programmatic and config-loading options in earlier sections, since they are taken into account long before the configuration that is prepared for merging.

include

Type: MatchPattern | Array<MatchPattern> (MatchPattern)

This option is a synonym for “test”.

exclude

Type: MatchPattern | Array<MatchPattern> (MatchPattern)

If any of patterns match, the current configuration object is considered inactive and is ignored during config processing. This option is most useful when used within an overrides option object, but it’s allowed anywhere.

Note: These toggles do not affect the programmatic and config-loading options in earlier sections, since they are taken into account long before the configuration that is prepared for merging.

ignore

Type: Array<MatchPattern> (MatchPattern)

Placement: Not allowed inside of presets

If any of the patterns match, Babel will immediately stop all processing of the current build. For example, a user may want to do something like

ignore: [
 "./lib",
]
Copy

to explicitly disable Babel compilation of files inside the lib directory.

Note: This option disables all Babel processing of a file. While that has its uses, it is also worth considering the “exclude” option as a less aggressive alternative.

only

Type: Array<MatchPattern> (MatchPattern)

Placement: Not allowed inside of presets

If all of the patterns fail to match, Babel will immediately stop all processing of the current build. For example, a user may want to do something like

 only: [
 "./src",
]

Copy

to explicitly enable Babel compilation of files inside the src directory while disabling everything else.

Note: This option disables all Babel processing of a file. While that has its uses, it is also worth considering the “test”/”include” options as a less aggressive alternative.

Source Map options

inputSourceMap

Type: boolean | SourceMap

Default: true

true will attempt to load an input sourcemap from the file itself, if it contains a //# sourceMappingURL=… comment. If no map is found, or the map fails to load and parse, it will be silently discarded.

If an object is provided, it will be treated as the source map object itself.

sourceMaps

Type: boolean | “inline” | “both”

Default: false

  • true to generate a sourcemap for the code and include it in the result object.
  • “inline” to generate a sourcemap and append it as a data URL to the end of the code, but not include it in the result object.
  • “both” is the same as inline, but will include the map in the result object.

@babel/cli overloads some of these to also affect how maps are written to disk:

  • true will write the map to a .map file on disk
  • “inline” will write the file directly, so it will have a data: containing the map
  • “both” will write the file with a data: URL and also a .map.

Note: These options are bit weird, so it may make the most sense to just use true and handle the rest in your own code, depending on your use case.

sourceMap

This is an synonym for sourceMaps. Using sourceMaps is recommended.

sourceFileName

Type: string

Default: path.basename(opts.filenameRelative) when available, or “unknown”

The name to use for the file inside the source map object.

sourceRoot

Type: string

The sourceRoot fields to set in the generated source map, if one is desired.

Misc options

sourceType

Type: “script” | “module” | “unambiguous”

Default: “module”

  • script” – Parse the file using the ECMAScript Script grammar. No import/export statements allowed, and files are not in strict mode.
  • module” – Parse the file using the ECMAScript Module grammar. Files are automatically strict, and import/export statements are allowed.
  • unambiguous” – Consider the file a “module” if import/export statements are present, or else consider it a “script”. unambiguous can be quite useful in contexts where the type is unknown, but it can lead to false matches because it’s perfectly valid to have a module file that does not use import/export statements

This option is important because the type of the current file affects both parsing of input files, and certain transforms that may wish to add import/require usage to the current file.

For instance, @babel/plugin-transform-runtime relies on the type of the current document to decide whether to insert an import declaration, or a require() call. @babel/preset-env also does the same for its “useBuiltIns” option. Since Babel defaults to treating files are ES modules, generally these plugins/presets will insert import statements. Setting the correct sourceType can be important because having the wrong type can lead to cases where Babel would insert import statements into files that are meant to be CommonJS files. This can be particularly important in projects where compilation of node_modules dependencies is being performed, because inserting an import statements can cause Webpack and other tooling to see a file as an ES module, breaking what would otherwise be a functional CommonJS file.

Note: This option will not affect parsing of .mjs files, as they are currently hard-coded to always parse as “module” files.

highlightCode

Type: boolean

Default: true

Highlight tokens in code snippets in Babel’s error messages to make them easier to read.

wrapPluginVisitorMethod

Type: (key: string, nodeType: string, fn: Function) => Function

Allows users to add a wrapper on each visitor in order to inspect the visitor process as Babel executes the plugins.

  • key is a simple opaque string that represents the plugin being executed.
  • nodeType is the type of AST node currently being visited.
  • fn is the visitor function itself.

Users can return a replacement function that should call the original function after performing whatever logging and analysis they wish to do.

parserOpts

Type: {}

An opaque object containing options to pass through to the parser being used.

generatorOpts

Type: {}

An opaque object containing options to pass through to the code generator being used.

Code Generator options

retainLines

Type: boolean

Default: false

Babel will make an effort to generate code such that items are printed on the same line that they were on in the original file. This option exists so that users who cannot use source maps can get vaguely useful error line numbers, but it is only a best-effort, and is not guaranteed in all cases with all plugins.

compact

Type: boolean | “auto”

Default: “auto”

“auto” will set the value by evaluating code.length > 500_000

All optional newlines and whitespace will be omitted when generating code in compact mode.

minified

Type: boolean

Default: false

Includes compact: true, omits block-end semicolons, omits () from new Foo() when possible, and may output shorter versions of literals.

auxiliaryCommentBefore

Type: string

Allows specifying a prefix comment to insert before pieces of code that were not present in the original file.

Note: The definition of what is and isn’t present in the original file can get a little ugly, so usage of this option is not recommended. If you need to annotate code somehow, it is better to do so using a Babel plugin.

auxiliaryCommentAfter

Type: string

Allows specifying a prefix comment to insert after pieces of code that were not present in the original file.

Note: The definition of what is and isn’t present in the original file can get a little ugly, so usage of this option is not recommended. If you need to annotate code somehow, it is better to do so using a Babel plugin.

comments

Type: boolean

Default: true

Provides a default comment state for shouldPrintComment if no function is given. See the default value of that option for more info.

shouldPrintComment

Type: (value: string) => boolean

Default without minified: (val) => opts.comments || /@license|@preserve/.test(val)

Default with minified: () => opts.comments

A function that can decide whether a given comment should be included in the output code from Babel.

AMD / UMD / SystemJS module options

moduleIds

Type: boolean

Default: !!opts.moduleId

Enables module ID generation.

moduleId

Type: string

A hard-coded ID to use for the module. Cannot be used alongside getModuleId.

getModuleId

Type: (name: string) => string

Given the babel-generated module name, return the name to use. Returning a falsy value will use the original name.

moduleRoot

Type: string

A root path to include on generated module names.

Options Concepts

MatchPattern

Type: string | RegExp | (filename: string | void, context: { callee: { name: string } | void, envName: string ) => boolean

Several Babel options perform tests against file paths. In general, these options support a common pattern approach where each pattern can be

  • string – A file path with simple support for * and ** as full slug matches. Any file or parent folder matching the pattern counts as a match. The path follows Node’s normal path logic, so on POSIX is must be /-separated, but on Windows both / and \ are supported.
  • RegExp – A regular expression to match against the normalized filename. On POSIX the path RegExp will run against a /-separated path, and on Windows it will be on a \-separated path.

Importantly, if either of these are used, Babel requires that the filename option be present, and will consider it an error otherwise.

  • (filename: string | void, context: { callee: { name: string } | void, envName: string }) => boolean is a general callback that should return a boolean to indicate whether it is a match or not. The function is passed the filename or undefined if one was not given to Babel. It is also passed the current envName and callee options that were specified by the top-level call to Babel.

Merging

Babel’s configuration merging is relatively straightforward. Options will overwrite existing options when they are present, and their value is not undefined, with a few special cases:

  • parserOpts objects are merged, rather than replaced, using the same logic as top-level options.
  • generatorOpts objects are merged, rather than replaced, using the same logic as top-level options.
  • plugins and presets are replaced based on the identity of the plugin/preset object/function itself combined with the name of the entry.

Plugin/Preset merging

As an example, consider a config with:

Plugin/Preset merging

As an example, consider a config with:

 plugins: [
 './other',
 ['./plug', { thing: true, field1: true }]
],
overrides: [{
 plugins: [
   ['./plug', { thing: false, field2: true }],
 ]
}]

The overrides item will be merged on top of the top-level plugins. Importantly, the plugins array as a whole doesn’t just replace the top-level one. The merging logic will see that “./plug” is the same plugin in both cases, and { thing: false, field2: true } will replace the original options, resulting in a config as

 plugins: [
 './other',
 ['./plug', { thing: false, field2: true }],
],

Since merging is based on identity + name, it is considered an error to use the same plugin with the same name twice in the same plugins/presets array. For example

 plugins: [
 './plug',
 './plug',
]

is considered an error, because it’s identical to plugins: [‘./plug’]. Additionally, evenplugins:

[
 ['./plug', {one: true}],
 ['./plug', {two: true}]
]

is considered an error, because the second one would just always replace the first one.

If you actually do want to instantiate two separate instances of a plugin, you must assign each one a name to disambiguate them. For example:

plugins: [
 ['./plug', {one: true}, "first-instance-name"],
 ['./plug', {two: true}, "second-instance-name"]
]

because each instance has been given a unique name and this a unique identity.

Plugin/Preset entries

PluginEntry / PresetEntry

Individual plugin/preset items can have several different structures:

  • EntryTarget – Individual plugin
  • [EntryTarget, EntryOptions] – Individual plugin w/ options
  • [EntryTarget, EntryOptions, string] – Individual plugin with options and name (see merging for more info on names)
  • ConfigItem – A plugin configuration item created by babel.createConfigItem().

The same EntryTarget may be used multiple times unless each one is given a different name, and doing so will result in a duplicate-plugin/preset error.

That can be a little hard to read, so as an example:

 plugins: [
 // EntryTarget
 '@babel/plugin-transform-classes',

 // [EntryTarget, EntryOptions]
 ['@babel/plugin-transform-arrow-functions', { spec: true }],

 // [EntryTarget, EntryOptions, string]
 ['@babel/plugin-transform-for-of', { loose: true }, "some-name"],

 // ConfigItem
 babel.createConfigItem(require("@babel/plugin-transform-spread")),
]

EntryTarget

Type: string | {} | Function

A plugin/preset target can come from a few different sources:

  • string – A require-style path or plugin/preset identifier. Identifiers will be passed through name normalization.
  • {} | Function – An actual plugin/preset object or function after it has been require()ed.

EntryOptions

Type: undefined | {} | false

Options are passed through to each plugin/preset when they are executed. undefined will be normalized to an empty object.

false indicates that an entry is entirely disabled. This can be useful in contexts where ordering is important, but a separate condition is needed to decide if something is enabled. For instance:

 plugins: [
 'one',
 ['two', false],
 'three',
],
overrides: [{
 test: "./src",
 plugins: [
   'two',
 ]
}]

would enable the two plugin for files in src, but two would still execute between one and three.

Name Normalization

By default, Babel expects plugins to have a babel-plugin- or babel-preset- prefix in their name. To avoid repetition, Babel has a name normalization phase will automatically add these prefixes when loading items. This boils down to a few primary rules:

  • Absolute paths pass through untouched.
  • Relative paths starting with ./ pass through untouched.
  • References to files within a package are untouched.
  • Any identifier prefixed with module: will have the prefix removed but otherwise be untouched.
  • plugin-/preset- will be injected at the start of any @babel-scoped package that doesn’t have it as a prefix.
  • babel-plugin-/babel-preset- will be injected as a prefix any unscoped package that doesn’t have it as a prefix.
  • babel-plugin-/babel-preset- will be injected as a prefix any @-scoped package that doesn’t have it anywhere in their name.
  • babel-plugin/babel-preset will be injected as the package name if only the @-scope name is given.

Here are some examples, when applied in a plugin context:

Input Normalized
“/dir/plugin.js”
“/dir/plugin.js”
“./dir/plugin.js”“./dir/plugin.js”
“mod”“babel-plugin-mod”
“mod/plugin”“mod/plugin”
“babel-plugin-mod”“babel-plugin-mod”
“@babel/mod”“@babel/plugin-mod”
@babel/plugin-mod”“@babel/plugin-mod”
“@babel/mod/plugin”“@babel/mod/plugin”
“@scope”“@scope/babel-plugin”
“@scope/babel-plugin”“@scope/babel-plugin”
“@scope/mod”“@scope/babel-plugin-mod”
“@scope/babel-plugin-mod”“@scope/babel-plugin-mod”
“@scope/prefix-babel-plugin-mod”“@scope/prefix-babel-plugin-mod”
“@scope/mod/plugin”“@scope/mod/plugin”
“module:foo”“foo”

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
Use Strict in JavaScript
JavaScript Variables