When to use babel.config.js and .babelrc

JavascriptCompiler ConstructionBabeljs

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

There seems to be some difference between the two configurations,

Looking at this question :

https://stackoverflow.com/questions/50147915/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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMIIView Question on Stackoverflow
Solution 1 - JavascriptBodmanView Answer on Stackoverflow
Solution 2 - JavascriptPatrickView Answer on Stackoverflow