PDH 개발 공부

[Babel.js] 기본 개념 (1) 본문

JavaScript/Babel

[Babel.js] 기본 개념 (1)

IFBB 2021. 8. 4. 08:40

Babel 이란?

  • 웹 애플리케이션 기반 기술 중 하나로 입/출력이 모두 자바스크립트 코드인 컴파일러 초기의 바벨은 ES6 코드를 ES5 코드로 변환해 주는 컴파일러였으나, 현재는 바벨을 이용해서 리액트 JSX 문법, 타입스크립트, 코드 압축,제안(proposal) 단계에 있는 문법 등을 사용할 수 있음

Core 라이브러리

  1. 변환 규칙을 소스에 적용해서 변환 파일을 생성한다.
  2. 변환 규칙은 가지고 있지 않다
  3. 바벨 플러그인이 변환 규칙을 가지고 있다.

코어 라이브러리 설치

$ npm i -D @babel/core

코어 라이브러리 사용해보기

const babel = require('@babel/core');
const result = babel.transform("const fn = () => 1;", {});

console.log(result);

결과

{
  metadata: {},
  options: {
    assumptions: {},
    targets: {},
    cloneInputAst: true,
    babelrc: false,
    configFile: false,
    browserslistConfigFile: false,
    passPerPreset: false,
    envName: 'development',
    cwd: 'C:\\Users\\admin\\WebstormProjects\\react-practices\\01.basics\\babel-practices\\ex01',
    root: 'C:\\Users\\admin\\WebstormProjects\\react-practices\\01.basics\\babel-practices\\ex01',
    rootMode: 'root',
    plugins: [],
    presets: [],
    parserOpts: { sourceType: 'module', sourceFileName: undefined, plugins: [] },
    generatorOpts: {
      filename: undefined,
      auxiliaryCommentBefore: undefined,
      auxiliaryCommentAfter: undefined,
      retainLines: undefined,
      comments: true,
      shouldPrintComment: undefined,
      compact: 'auto',
      minified: undefined,
      sourceMaps: false,
      sourceRoot: undefined,
      sourceFileName: 'unknown'
    }
  },
  ast: null,
  code: 'const fn = () => 1;',
  map: null,
  sourceType: 'module'
}

CLI 사용법

  1. 설치
    $ npm i -D @babel/core @babel/cli
  2. 소스 파일 작성(EX6)
  3. 변환하기
    $ npx babel src -d dist
    Successfully compiled 1 file with Babel (334ms).

초기코드

'use strict'

// 블록 스코프 변수(ES6)
const users = [{
    no: 0,
    name: '마이콜',
    email: 'michol@gmail.com'
},{
    no: 1,
    name: '둘리',
    email: 'dooly@gmail.com'
}];

// 객체분해(ES6)
function print({no, name, email}) {
    // 템플릿 문자열(ES6)
    console.log(`${no}: ${name} : ${email}`);
}

// for..of(ES6)
for(let user of users) {
    print(user);
}

변환코드

'use strict'; // 블록 스코프 변수(ES6)

const users = [{
  no: 0,
  name: '마이콜',
  email: 'michol@gmail.com'
}, {
  no: 1,
  name: '둘리',
  email: 'dooly@gmail.com'
}]; // 객체분해(ES6)

function print({
  no,
  name,
  email
}) {
  // 템플릿 문자열(ES6)
  console.log(`${no}: ${name} : ${email}`);
} // for..of(ES6)


for (let user of users) {
  print(user);
}

'JavaScript > Babel' 카테고리의 다른 글

[Babel.js] Env Preset (3)  (1) 2021.08.04
[Babel.js] 플러그인 적용 (2)  (0) 2021.08.04
Comments