Skip to content

BabelJs - CLI

Babel comes with a powerful command-line interface (CLI), @babel/cli, which allows you to transpile JavaScript files directly from your terminal. This is useful for simple build processes, scripting, or integrating Babel into other command-line workflows.

First, you need to install @babel/cli and @babel/core in your project. It’s recommended to install them as local development dependencies.

  1. Initialize your project (if you haven’t already):
mkdir babel-cli-example
cd babel-cli-example
npm init -y
  1. Install Babel CLI and Core:
npm install --save-dev @babel/core @babel/cli

You’ll also likely need a preset, such as @babel/preset-env, to tell Babel which transformations to apply:

npm install --save-dev @babel/preset-env

Your package.json devDependencies will now include these:

{
// ... other package.json content ...
"devDependencies": {
"@babel/cli": "^7.x.x",
"@babel/core": "^7.x.x",
"@babel/preset-env": "^7.x.x"
}
}

Babel needs a configuration file to know which presets and plugins to use. Create a babel.config.json (or .babelrc.json) file in your project root:

babel.config.json
{
"presets": ["@babel/preset-env"]
}

This tells Babel to use @babel/preset-env for transformations. You can configure targets within @babel/preset-env if needed (see ‘Project Setup’ or ‘Polyfills’ chapters).

Let’s create a simple JavaScript file with modern syntax. Create src/index.js:

src/index.js
const message = "Hello from Babel CLI!";
const greet = (name) => `${message} Welcome, ${name}!`;
console.log(greet("Developer"));
[1, 2, 3].map(n => n * 2).forEach(n => console.log(n));

Transpiling a Single File to Standard Output

Section titled “Transpiling a Single File to Standard Output”

You can transpile a file and print the output to your terminal using npx babel <filepath>:

npx babel src/index.js

Output in terminal (example):

"use strict";
var message = "Hello from Babel CLI!";
var greet = function greet(name) {
return "".concat(message, " Welcome, ").concat(name, "!");
};
console.log(greet("Developer"));
[1, 2, 3].map(function (n) {
return n * 2;
}).forEach(function (n) {
return console.log(n);
});

npx is a tool that comes with npm to execute package binaries. It ensures you’re using the version of @babel/cli installed in your project.

Transpiling a Single File to an Output File

Section titled “Transpiling a Single File to an Output File”

To save the transpiled code to a new file, use the --out-file (or -o) option:

npx babel src/index.js --out-file lib/index.js

This will create a lib directory (if it doesn’t exist) and save the transpiled code to lib/index.js.

To transpile all JavaScript files in a directory (e.g., src/) and output them to another directory (e.g., lib/), use the --out-dir (or -d) option:

npx babel src --out-dir lib

This will process all .js, .jsx, .es6, .es files in src/, maintain the directory structure, and save the transpiled files to lib/.

  • --out-file or -o: Compile a single file to a specified output file.
  • --out-dir or -d: Compile an entire directory to a specified output directory.
  • --watch or -w: Watch files for changes and recompile automatically. Very useful during development.
  • --source-maps: Generate source maps. Can be true, inline, or both. Source maps help you debug your original code even after transpilation.
  • --presets: Specify presets directly on the command line (though config files are generally preferred). Example: --presets=@babel/preset-env,@babel/preset-react
  • --plugins: Specify plugins directly. Example: --plugins=@babel/plugin-transform-arrow-functions
  • --ignore <pattern>: A glob pattern of files to ignore. Example: --ignore "**/*.test.js"
  • --copy-files: When compiling a directory, copy over files that Babel doesn’t process (e.g., JSON files, images).
  • --extensions <exts>: A comma-separated list of file extensions to process. Default: .js,.jsx,.es6,.es. Example: --extensions ".ts,.js" for TypeScript projects.
  • --no-babelrc: Disable the use of .babelrc (older config) files. babel.config.json is usually still loaded. Use --config-file false to disable loading of babel.config.json.
npx babel src --out-dir lib --watch --source-maps

This command will transpile the src directory to lib, generate source maps, and then continue watching for any changes in src. When a file is changed, it will be re-transpiled automatically.

Suppose you have test files like src/utils.test.js that you don’t want to transpile to the lib directory:

npx babel src --out-dir lib --ignore "src/**/*.test.js","src/**/__tests__"

It’s common practice to add Babel CLI commands to the scripts section of your package.json file.

package.json
{
// ...
"scripts": {
"build": "babel src --out-dir lib --source-maps",
"watch": "babel src --out-dir lib --source-maps --watch"
},
// ...
}

Now you can run:

  • npm run build to transpile your code once.
  • npm run watch to transpile and watch for changes.

Using Specific Plugins/Presets via CLI (Less Common)

Section titled “Using Specific Plugins/Presets via CLI (Less Common)”

While it’s generally better to manage presets and plugins in a configuration file, you can specify them on the command line if needed. For this, you’d need to install the specific plugin as well. For instance, if you wanted to only use the arrow function transform without a config file:

npm install --save-dev @babel/plugin-transform-arrow-functions
npx babel src/index.js --out-file lib/index.js --plugins=@babel/plugin-transform-arrow-functions

This approach is less common for full projects because managing many plugins via CLI arguments becomes cumbersome. @babel/preset-env usually handles including necessary transform plugins.

  • Server-side applications (Node.js): When you want to use modern JavaScript features in your Node.js code but need to support older Node versions.
  • Simple build processes: For smaller projects or libraries where a complex bundler like Webpack isn’t necessary.
  • Utility scripts: When writing command-line tools or scripts in modern JavaScript.
  • Integration with other tools: As part of a larger build pipeline orchestrated by shell scripts or other task runners.

The Babel CLI is a versatile tool for JavaScript transpilation. For client-side browser applications, it’s often used in conjunction with module bundlers (like Webpack or Parcel) which use @babel/core programmatically via loaders (e.g., babel-loader). However, for many other scenarios, the CLI provides a direct and effective way to leverage Babel’s power.

For detailed CLI options, always refer to the official documentation: https://babeljs.io/docs/babel-cli