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:
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
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:
{ "presets": ["@babel/preset-env"] }
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
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).