User Tools

Site Tools


java-script:babel

Babel

Use cases

Babel was mainly used to transpile (compile) ES6 code into ES5 or older version of ES (ECMAScript).
Latest versions of Node.js (for example 16.15.1) already has good support for ES6, so babel may not be needed.

But, there are still situations where using Babel can be beneficial:

  1. Latest JavaScript Features: Babel lets you use the latest JavaScript features that may not be supported yet in your target environments. This includes features that are in the proposal stage and are not yet part of an official ECMAScript standard.
  2. Browser Compatibility: If you're developing a web application that needs to support older browsers (like Internet Explorer), Babel is crucial. You can compile your JavaScript to ensure it works correctly on all browsers you need to support.
  3. React/JSX: If you're using React or another library that uses JSX, Babel is necessary to compile JSX into regular JavaScript.
  4. Using TypeScript: Babel can be used to compile TypeScript to JavaScript, if you're using TypeScript for static type-checking.
  5. Minification: Babel can be used to minify your code, making the size of your JavaScript files smaller and thereby improving load times.
  6. Code Transformations: Babel has plugins that allow for code transformations which can help you write cleaner or more efficient code. For instance, @babel/plugin-transform-runtime can help to avoid duplication in your compiled output.

Install babel packages for a project

This will create a node-modules folder containing a lot of modules:

npm install @babel/core @babel/preset-env @babel/node

Output:

added 248 packages, and audited 249 packages in 40s

58 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Create .babelrc

Inside your project in the main directory create a file called .babelrc.
This will indicate babel which presets to use to transpile the ES6 code in ES5 code:

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

Run our transpiled code (from ES6 to ES5)

This command will transpile and run the code on the fly:

npx babel-node ./src/index.js

If the program has some arguments:

npx babel-node ./src/index.js 5 5

View transpiled code

If we want to examine the transpiled code, we'll need to install the babel command line:

npm install @babel/cli

Output:

added 29 packages, and audited 278 packages in 5s

61 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

Next, add a script entry in the package.json file:

{
  "scripts": {
    "build": "babel src -d dist"
  }
}

Next, we can run:

npm run build

Transpiled code are now in the dist folder:

> build
> babel src -d dist

Successfully compiled 2 files with Babel (423ms).
java-script/babel.txt · Last modified: 2023/08/03 03:09 by odefta