Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 21, 2022 07:57 pm GMT

Short Babel memo to configure it!

If you're a Javascript developper, chances that you have heard about Babel one day are very high.
Most of the time we don't necessary need to configure it ourself, because it is extremely common to use a starter or some boilerplate that come up with the basic configuration.
BUT sometimes we need to dig into that and that's my case, I am terrible at memorize all of thoses settings and It is extremely easy to waste time with that. So this post is simply me sharing my memo note about using Babel.

A quick reminder: what is babel

Babel is a JavaScript compiler. This is mainly use to transform your code into a compatible version of Javascript in most environnements and browsers.

Example from the official documentation:

// Babel Input: ES2015 arrow function[1, 2, 3].map(n => n + 1);// Babel Output: ES5 equivalent[1, 2, 3].map(function(n) {  return n + 1;});

Babel installation

Install babel:

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

A project need a babel config file.
There are 2 differents types:

  • Project-wide configuration
    • babel.config.* files, with the following extensions: .json, .js, .cjs, .mjs.
  • File-relative configuration
    • .babelrc.* files, with the following extensions: .json, .js, .cjs, .mjs.
    • .babelrc file, with no extension.
    • package.json files, with a "babel" key.

Whatever your pick, this file contains your presets and plugins.
Preset and plugins are used to apply code transformation.

For example the plugin @babel/plugin-transform-arrow-functions is used to transform array functions into ES5 compatible function expressions:

const fn = () => 1;// converted tovar fn = function fn() {  return 1;};

How to use

To use babel, we first have to install each preset or plugins.

If you need to use modern Javascript, we need preset-env

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

To compile Typescript into Javascript use: preset-typescript

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

Or React.js: preset-react

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

In the configuration file (here babel.config.json model):

{  "presets": ["@babel/preset-typescript", "@babel/env", "@babel/preset-react"],  "plugins": ["@babel/plugin-transform-arrow-functions"]}

Don't forget some options might be avalaible to certains preset and plugins! (see docs).

Finally compile for example a Typescript code:

npx babel index.ts --out-file ./dist/index.js

Hope it helps some people into their project configuration struggle! Have a good day.

Source


Original Link: https://dev.to/leopold/short-babel-memo-to-configure-it-19c7

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To