When to use babel.config.js and .babelrc

I was learning Babel and wanted to learn how to configure Babel. I found two ways to configure Babel: by creating babel.config.js and .babelrc file. Under what circumstances should we prefer one config file over the other?


Solution 1:

From the docs https://babeljs.io/docs/en/config-files#project-wide-configuration

Babel has two parallel config file formats which can be used together, or independently.

Project-wide configuration
    babel.config.json files, with the different extensions

File-relative configuration
    .babelrc.json files, with the different extensions
    package.json files with a "babel" key

Babel loads .babelrc.json files, or an equivalent one using the supported extensions, by searching up the directory structure starting from the "filename" being compiled

Given that information

.babelrc would be useful if you want to run certain transformations / plugins on a subset of files /directories. Maybe you have 3rd party libraries that you don't want to be transformed/changed by babel.

babel.config.json is useful if you have multiple packages (ie multiple package.json) directories in your project that utilize a single babel config. This is less common.

If your question is about file extensions (ie .js vs .json) with respect to babel configurations

Using .js exposes a babel config api.

https://babeljs.io/docs/en/config-files#config-function-api

Keep in mind this increases complexity with regards to caching, most of the time it's best to use .json static configurations

Solution 2:

There seems to be some difference between the two configurations,

Looking at this question :

Jest transformIgnorePatterns not working

Sometimes, certain features only work with a certain file, this is extremely vague and certainly not documented. (I can confirm the above mentioned problem exists, and renaming the config file solves it)

Also, some other times babel configuration files are downright ignored, as in the case of webpack and babel-loader. You'd expect babel to load the .babelrc file found in the root of the project, but it turns out it will ignore it and run the options provided within Webpack.

So the answer unfortunately is a bit vague, and the lack of documentation on how these features work does not improve the situation.