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 core-js@2 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


Leave a Comment