Search code examples
javascriptbabeljs

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

  • 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