Babel이란?
- JavaScript 컴파일러이다.
- 이전 버전과 호환되는 JavaScript 버전으로 변환하는데 주로 사용한다.
Babel 사용 이유
- JavaScript 문법은 꾸준히 진화고 있다.
- JavaScript 문법이 꾸준히 진화하고 있는데 브라우저가 지원을 하지 않으면 동작하지 않는다.
- Babel이 하위 브라우저에서도 동작할 수 있도록 컴파일을 해준다.
- JavaScript를 실행하는 방법이 다양하다.
- 브라우저에서 실행
- Node.js에서 실행
- Node.js 환경에서 작업한 코드를 브라우저에서 동작 할 수 있게 컴파일 해준다.
Babel 기본 사용 방법
- Node.js 환경이 필요하다.
- Node.js 환경에서 babel을 사용하면 파일에 접근해서 코드를 변환해준다.
- babel은 기본적으로 JavaScript로 구성되어 있고 npm을 통해 쉽게 설치가 가능 하다.
사용 방법
- Babel 설치 및 Preset 또는 Plugin 설치
- 설정 파일 작성
- .babelrc : 특정 경로에만 적용할 속성이 있을 때
- babel.config.js : 루트 경로로 부터 모든 파일에 동일한 설정을 적용할 때
- 원하는 파일 변환
Babel 설치
npm install @babel/core @babel/cli
Preset 설치
npm install @babel/preset-env
설정 파일 작성 (Presets)
{
"presets" : ["@babel/preset-env"]
}
Plugin 설치
npm install @babel/plugin-transform-modules-commonjs
설정 파일 작성 (Plugins)
{
"plugins": ["@babel/plugin-transform-modules-commonjs"]
}
파일 변환
npx babel [바꿀파일] --out-file [내보낼파일명]
실습
실습 환경 구성
mkdir babel_practice
cd babel_practice
npm init -y
최신문법 ES5 문법으로 변환
- babel 설치 및 Preset 설치
npm install @babel/core @babel/cli @babel/preset-env
- 설정 파일 작성 (Presets)
.babelrc
{
"presets" : ["@babel/preset-env"]
}
- 변환할 파일 생성
newSyntax.js
class Greet {
static printMsg(message) {
console.log(`${message} wolrd!`);
}
}
Greet.printMsg("Hello");
const arr = ["a", "b", "c", "d", "e"];
console.log(arr.at(-1));
- 변환
npx babel newSyntax.js --out-file dist/oldSyntax.js
- 결과
dist/oldSyntax.js
"use strict";
function _typeof(obj) {
"@babel/helpers - typeof";
return (
(_typeof =
"function" == typeof Symbol && "symbol" == typeof Symbol.iterator
? function (obj) {
return typeof obj;
}
: function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}),
_typeof(obj)
);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", { writable: false });
return Constructor;
}
function _toPropertyKey(arg) {
var key = _toPrimitive(arg, "string");
return _typeof(key) === "symbol" ? key : String(key);
}
function _toPrimitive(input, hint) {
if (_typeof(input) !== "object" || input === null) return input;
var prim = input[Symbol.toPrimitive];
if (prim !== undefined) {
var res = prim.call(input, hint || "default");
if (_typeof(res) !== "object") return res;
throw new TypeError("@@toPrimitive must return a primitive value.");
}
return (hint === "string" ? String : Number)(input);
}
var Greet = (function () {
function Greet() {
_classCallCheck(this, Greet);
}
_createClass(Greet, null, [
{
key: "printMsg",
value: function printMsg(message) {
console.log("".concat(message, " wolrd!"));
},
},
]);
return Greet;
})();
Greet.printMsg("Hello");
var arr = ["a", "b", "c", "d", "e"];
console.log(arr.at(-1));
node.js에서 import 구문 사용을 위한 변환
- babel 설치 및 Plugin 설치
npm install @babel/core @babel/cli @bebel/plugin-transform-modules-commonjs
- express 모듈 설치
npm install express
- 설정 파일 작성 (Plugins)
.babelrc
{
"plugins" : ["@babel/plugin-transform-modules-commonjs"]
}
- 변환할 파일 생성
server.js
import express from "express";
const app = express();
app.listen(3000, () => {
console.log(`Server Start`);
});
- 변환
npx babel server.js --out-file dist/server.js
- 결과
dist/server.js
"use strict";
var _express = _interopRequireDefault(require("express"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
const app = (0, _express.default)();
app.listen(3000, () => {
console.log(`Server Start`);
});
jsx 문법 변환
- babel 설치 및 Preset 설치
npm install @babel/core @babel/cli @babel/preset-react
- 설정 파일 작성 (Presets)
.babelrc
{
"presets": ["@babel/preset-react"]
}
- 변환할 파일 생성
app.js
class App {
render() {
return <div>Hello World!</div>;
}
}
- 변환
npx babel app.js --out-file dist/app.js
- 결과
class App {
render() {
return React.createElement("div", null, "Hello World!");
}
}
참고
Babel - 공식 문서
바벨과 함께 트랜스파일 해보기