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

  1. module.exports = function (api) {
  2. api.cache(true);
  3. const presets = [ ... ];
  4. const plugins = [ ... ];
  5. return {
  6. presets,
  7. plugins
  8. };
  9. }

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.

  1. {
  2. "presets": [...],
  3. "plugins": [...]
  4. }

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:

  1. {
  2. "name": "my-package",
  3. "version": "1.0.0",
  4. "babel": {
  5. "presets": [ ... ],
  6. "plugins": [ ... ],
  7. }
  8. }

.babelrc.js

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

  1. const presets = [ ... ];
  2. const plugins = [ ... ];
  3. module.exports = { presets, plugins };

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

  1. const presets = [ ... ];
  2. const plugins = [ ... ];
  3. if (process.env["ENV"] === "prod") {
  4. plugins.push(...);
  5. }
  6. module.exports = { presets, plugins };

Using the CLI (@babel/cli)

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

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

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