BabelJs - CLI
BabelJS - Command Line Interface (CLI)
Section titled “BabelJS - Command Line Interface (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.
Installation
Section titled “Installation”First, you need to install @babel/cli and @babel/core in your project. It’s recommended to install them as local development dependencies.
- Initialize your project (if you haven’t already):
mkdir babel-cli-examplecd babel-cli-examplenpm init -y- Install Babel CLI and Core:
npm install --save-dev @babel/core @babel/cliYou’ll also likely need a preset, such as @babel/preset-env, to tell Babel which transformations to apply:
npm install --save-dev @babel/preset-envYour 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" }}Configuration
Section titled “Configuration”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:
{ "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).
Basic Usage
Section titled “Basic Usage”Let’s create a simple JavaScript file with modern syntax. Create 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.jsOutput 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.jsThis will create a lib directory (if it doesn’t exist) and save the transpiled code to lib/index.js.
Transpiling an Entire Directory
Section titled “Transpiling an Entire Directory”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 libThis will process all .js, .jsx, .es6, .es files in src/, maintain the directory structure, and save the transpiled files to lib/.
Common CLI Options
Section titled “Common CLI Options”--out-fileor-o: Compile a single file to a specified output file.--out-diror-d: Compile an entire directory to a specified output directory.--watchor-w: Watch files for changes and recompile automatically. Very useful during development.--source-maps: Generate source maps. Can betrue,inline, orboth. 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.jsonis usually still loaded. Use--config-file falseto disable loading ofbabel.config.json.
Example: Watching for Changes
Section titled “Example: Watching for Changes”npx babel src --out-dir lib --watch --source-mapsThis 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.
Example: Ignoring Test Files
Section titled “Example: Ignoring Test Files”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__"Using with npm Scripts
Section titled “Using with npm Scripts”It’s common practice to add Babel CLI commands to the scripts section of your package.json file.
{ // ... "scripts": { "build": "babel src --out-dir lib --source-maps", "watch": "babel src --out-dir lib --source-maps --watch" }, // ...}Now you can run:
npm run buildto transpile your code once.npm run watchto 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-functionsnpx babel src/index.js --out-file lib/index.js --plugins=@babel/plugin-transform-arrow-functionsThis 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.
When to use Babel CLI
Section titled “When to use Babel CLI”- 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