Configure babel 7 for node api

Frontend Development

Published about 1 month ago


A quick step to transpile your code for all browsers

APIs(Application Programming Interface) is one of the core of Software Development and for your API’s to be accessible on all browsers you need Babel to transpile your Javascript code to the supported ES5 version.


I used Babel often and it is one of the best out there.

After setting up your Node API project, and you can run it from your local machine using your scripts.

These are dependencies you need for babel to run properly. We need to install @babel/cli, @babel/node, @babel/core and @babel/preset-env. Checkout babel documentation here.

yarn add @babel/cli @babel/node @babel/core @babel/preset-env
After installing, add a .babelrc file to use preset-env plugin.

## .babelrc file
{
  "presets": [
    "@babel/preset-env"
  ]
}
To run your application through babel, we ar e going to setup a development and production script.

To do this, we will create a build script that delete dist folder and create a new dist folder whenever the script is run and compile our source code into that folder. Nodemon can be used for development so you can install nodemon.

yarn add nodemon --save-dev
Add this script to your package.json file.

## package.json"scripts": {   "build": "rm -rf dist/ && babel ./src --out-dir dist/ --ignore ./node_modules",   "start": "yarn build && node ./dist/index.js",   "start:dev": "nodemon --exec babel-node src/index.js"
}
For Development: yarn start:dev 
For Production: yarn start

I assume all your javascript file is in the src folder and that your entry file is index.js, you can change that if its not.

Thanks for following through.

Login