English 中文(简体)
BabelJs - Project Setup Using Babel 7
  • 时间:2024-11-03

BabelJS - Project setup using Babel 7


Previous Page Next Page  

The latest version of Babel, 7 released with changes to the already existing packages. The installation part remains the same as it was for Babel 6. The only difference in Babel 7 is that all the packages need to be installed with @babel/, for example @babel/core, @babel/preset-env, @babel/cp, @babel/polyfill, etc.

Here is a project setup created using babel 7.

Command

Execute the following command to start the project setup −

npm init

Install following packages

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

Here is the package.json created −

Install Packages

Now will create a .babelrc file in the root folder −

Create Babelrc

Create a folder src/ and add file main.js to it and write your code to transpile to es5.

src/main.js

let add = (a,b) => {
   return a+b;
}

command to transpile

npx babel src/main.js --out-file main_es5.js

main_es5.js

"use strict";

var add = function add(a, b) {
   return a + b;
};

The working of Babel 7 remains the same as Babel 6. The only difference is the pacakge installation with @babel.

There are some presets deprecated in babel 7. The pst is as follows −

    ES20xx presets

    babel-preset-env

    babel-preset-latest

    Stage presets in Babel

Also the year from the packages is removed - @babel/plugin-transform-es2015-classes is now @babel/plugin-transform-classes

We will see one more example of working with typescript and transpile it to Es2015 JavaScript using typescript preset and babel 7.

To work with typescript, we need typescript package to be installed as follows −

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

Create test.ts file in the src/ folder and write the code in typescript form −

test.ts

let getName = (person: string) => {
   return "Hello, " + person;
}

getName("Siya");

.babelrc

Babelrc Typescript

command

npx babel src/test.ts --out-file test.js

test.js

"use strict";

var getName = function getName(person) {
   return "Hello, " + person;
};

getName("Siya");
Advertisements