Configuring Babel (Advanced)
Babel presets are simply collections of pre-configured plugins, if you want to do something differently you manually specify plugins. This works almost exactly the same way as presets.
First install a plugin:
Then add the field to your .babelrc
.
{
+ "plugins": [
+ "transform-es2015-classes"
+ ]
}
This gives you much finer grained control over the exact transforms you are running.
For a full list of official plugins see the .
Also take a look at all the plugins that have been built by the community. If you would like to learn how to write your own plugin read the .
Many plugins also have options to configure them to behave differently. For example, many transforms have a “loose” mode which drops some spec behavior in favor of simpler and more performant generated code.
{
"plugins": [
- "transform-es2015-classes"
]
}
Babel plugins solve many different tasks. Many of them are development tools that can help you debugging your code or integrate with tools. There are also a lot of plugins that are meant for optimizing your code in production.
For this reason, it is common to want Babel configuration based on the
environment. You can do this easily with your .babelrc
file.
Babel will enable configuration inside of env
based on the current
environment.
The current environment will use process.env.BABEL_ENV
. When BABEL_ENV
is
not available, it will fallback to NODE_ENV
, and if that is not available it
will default to .
Unix
$ BABEL_ENV=production [COMMAND]
$ NODE_ENV=production [COMMAND]
Windows
$ SET BABEL_ENV=production
$ [COMMAND]
Tip: If you want your command to work across unix and windows platforms then use
cross-env
.
Manually specifying plugins? Plugin options? Environment-based settings? All this configuration might seem like a ton of repetition for all of your projects.
For this reason, we encourage the community to create their own presets. This could be a preset for the specific you are running, or maybe a preset for your entire .
It’s easy to create a preset. Say you have this .babelrc
file:
All you need to do is create a new project following the naming convention
babel-preset-*
(please be responsible with this namespace), and create two
files.
First, create a new package.json
file with the necessary dependencies
for
your preset.
{
"name": "babel-preset-my-awesome-preset",
"version": "1.0.0",
"author": "James Kyle <me@thejameskyle.com>",
"babel-preset-es2015": "^6.3.13",
"babel-plugin-transform-flow-strip-types": "^6.3.15"
}
}
Then create an index.js
file that exports the contents of your .babelrc
file, replacing plugin/preset strings with require
calls.
module.exports = function () {
presets: [
require("babel-preset-es2015"),
require("babel-preset-react")
],
plugins: [
require("babel-plugin-transform-flow-strip-types")
]
};