본문 바로가기
Web/Etc

[Babel] Getting Started

by llHoYall 2020. 9. 10.

Babel is a JS compiler or transpiler.

It compiles the newer JS to old JS for supporting many browsers. Because there is a lot of browsers that do not support the newer JS.

 

Babel can work with many bundlers or frameworks.

In this posting, let's find out the basic usage of Babel.

Installation

Create a new project for practicing Babel.

And then, install babel packages inside the project folder.

$ yarn add -D @babel/core @babel/cli @babel/preset-env

You can also use npm.

$ npm i -D @babel/core @babel/cli @babel/preset-env

Configuration

Create a babel.config.json file in the project folder. Babel recommends this type of file.

  • babel.config.json: project-wide configuration
  • .babelrc.json: only applies to a single part of a project
{
  "presets": [
    "@babel/env"
  ]
}

This means the Babel environment uses a predefined set.

Create a JS File

Let's make a src/main.js file with a newer syntax.

let nums = [1, 2, 3, 4, 5];
console.log(`${nums.map(e => e * e)}`);

Compiling

$ ./node_modules/.bin/babel src --out-dir lib

This command compiles all JS files in the src folder and puts the result to the lib folder.

The folder name is changeable.

 

Let's see the result.

"use strict";

var nums = [1, 2, 3, 4, 5];
console.log("".concat(nums.map(function (e) {
  return e * e;
})));

That's why we use the Babel.

Furthermore

These are the things you need to know to use the Babel better.

I might post about these contents in the future.

Let's just taste it.

Plugins

There are many plugins working with Babel. We usually use the plugins for React or TypeScript.

Plugins run before Presets.

Plugin ordering is first to last.

You can explicit Plugin in the configuration file.

{
  "plugins": ["plugin1", "plugin2"]
}

Presets

Presets can act as an array of Babel plugins or even a sharable options config.

You can create your own Preset.

Preset ordering is last to first.

Configuration

We can configure many things with a configuration file.

For example, you can specify a browser to support.

{
  "presets": [
    [
      "@babel/env",
      {
        "targets": {
          "edge": "17",
          "firefox": "60",
          "chrome": "67",
          "safari": "11.1",
        },
      }
    ]
  ]
}

'Web > Etc' 카테고리의 다른 글

[Web] Testing Rest API on VS Code  (0) 2020.09.30
[Gulp] Getting Started  (0) 2020.09.12
[Pug] Getting Started  (0) 2020.09.09
[Node] yarn  (0) 2020.08.30
[Node] NPM (Node Package Manager)  (0) 2020.08.30

댓글