Use a configuration directory with Babel

What is the issue?

Many users of Babel were complaining about the need of yet another dotfile in the root folder of your project.
While that is true, there is an elegant workaround to this.

Single file

You can simply extends your configuration using another configuration file and no need to pollute the root directory of your project anymore, we can create a config folder.
Here is an example:

- package.json:

JSON
        
{
  […]

  "babel": {
    "extends": "./config/babelrc"
  }
}
        
      

The configuration file is a regular Babel configuration.

- ./config/babelrc:

JSON
        
{
  "plugins": ["env"]
}
        
      

And here is what your project will look like:

Shell
        
$ tree .
.
├── config
│   └── babelrc
├── package.json
└── src
    └── index.js
        
      

Splitting by environment

If you have a more complex configuration and you would like to split it by the current $NODE_ENV or $BABEL_ENV value.
Here is the same example as above, but using multiple files:

- package.json:

JSON
        
{
  […]

  "babel": {
    "env": {
      "prod": {
        "extends": "./config/babelrc.prod"
      },
      "dev": {
        "extends": "./config/babelrc.dev"
      }
    }
  }
}
        
      
Shell
        
$ tree .
.
├── config
│   ├── babelrc.dev
│   └── babelrc.prod
├── package.json
└── src
    └── index.js
        
      

Babel 7

The env key in the Babel configuration can cause many unexpected behaviors. We recommend you to avoid using it.
Instead, we encourage you to use the new .babelrc.js file.

Since Babel 7 (which is currently in beta) we have added the support for a JavaScript format. Here is the same example with JS file:

- package.json:

JSON
        
{
  […]

  "babel": {
    "extends": "./config/babelrc.js"
  }
}
        
      

In this case the configuration is a bit different:
- ./config/babelrc.js:

JavaScript
        
module.exports =
  process.env.NODE_ENV === "prod"
    ? {
        plugins: ["env"]
      }
    : {}
        
      

Contact me

Say hello: sven.sauleau@xtuc.fr.

Ping me on Twitter: @svensauleau.

© XTUC SAS
N° SIRET : 821 797 891 00016, RCS Strasbourg TI 821 797 891