DEV Community

Leopold
Leopold

Posted on

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;
});
Enter fullscreen mode Exit fullscreen mode

Babel installation

Install babel:

npm install --save-dev @babel/core @babel/cli @babel/preset-env
Enter fullscreen mode Exit fullscreen mode

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 to

var fn = function fn() {
  return 1;
};
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

To compile Typescript into Javascript use: preset-typescript

npm install --save-dev @babel/preset-typescript
Enter fullscreen mode Exit fullscreen mode

Or React.js: preset-react

npm install --save-dev @babel/preset-react
Enter fullscreen mode Exit fullscreen mode

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

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

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
Enter fullscreen mode Exit fullscreen mode

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

Source

Top comments (0)