Babel-CLI set config value correctly

1.7k Views Asked by At

I am trying to add a build command that uses babel CLI to transpile my ES6. I am having difficult pointing it correctly to babelrc.

The file structure is roughly as follows:

root
    src
        index.js
        ...
    .babelrc
    .package.json

In my package.json, I originally tried the following:

  "scripts": {
    "build": "babel --out-dir dist src",
    ...
  },

But this gave an error because of the array destructuring notation I have used in my code. I think this is because it is not picking up my .babelrc file. Using

babel --presets=@babel/preset-env --out-dir dist src

instead fixes this problem. But I would rather I didn't have to specify plugins etc. here and rely on the .babelrc file instead.

From reading this issue, I get the impression babel looks for a config file in src rather than root . Looking at the documentation it seems there is an option for specifying a config file, but I can't quite get it to work correctly. My attempt:

babel --config-file .babelrc --out-dir dist src
4

There are 4 best solutions below

2
Brad Harker On

Babel should already pick up the .babelrc file automatically. If you want to add that preset, you should specify

{
  // ... more .babelrc up here
  "presets": ["@babel/preset-env"]
  // ... more .babelrc down here
}

in your .babelrc file.

But babel will automatically search for the closest .babelrc file in the directory starting at the entry file and working its way upwards (specified here at the bottom).

0
James Rushford On

You can use ./node_modules/.bin/babel in place of babel.

Worked for me this week.

Check point 3 in the overview from babel-cli https://babeljs.io/docs/en/usage

  1. And running this command to compile all your code from the src directory to lib:

./node_modules/.bin/babel src --out-dir lib

You can use the npm package runner that comes with [email protected] to shorten that command by replacing ./node_modules/.bin/babel with npx babel

0
Adhyan On

For Babel version 7.x, it looks for project-wide configuration in the file with name like this - babel.config.{json|js|cjs|mjs}. Check the documentation here.

1
Joshua Villaver On

In my end,

npx babel src/ -d lib/