October 26, 2020
이 글은 윤준성의 개발꼬맹이 시절, 혼자 노션에 공부하며 정리해둔 것 중 괜찮은 것을 추려올린 글입니다. 기술블로그 글 기고 목적으로 작성되지 않아, 가독성이 좋지 않거나 알 수 없는 워딩이 있을 수 있습니다.
컴파일: 한 언어로 작성된 소스 코드를 다른 언어로 변환하는 것
트랜스파일: 한 언어로 작성된 소스 코드를 비슷한 수준의 추상화를 가진 다른 언어로 변환하는 것
장점
// yarn add -D @babel/core
// 이후 babel.config.json 혹은 babel.config.js를 작성해야 한다.
const presets = [
[
"@babel/env",
{
targets: {
edge: "17",
firefox: "60",
chrome: "67",
safari: "11.1",
},
useBuiltIns: "usage",
"corejs": "3.6.4",
},
],
];
module.exports = { presets };// 바벨의 핵심 기능을 담는 패키지로 아래와 같은 것이 가능하다!
const babel = require('@babel/core');
babel.transform('code', optionsObject);하지만 아직까지는 ‘code’ 자리에 무엇을 넣어도 동일한 값이 리턴될 뿐이다.
# 아래 명령어는 src의 파일들을 lib이라는 폴더에 transpile 해준다
yarn add -D @babel/cli
yarn babel src --out-dir lib
# 플러그인을 추가할 수도 있다
# 아래의 명령어로 비로소 'code'속 화살표 함수는 function(){} 문법으로 대체된다
# 즉, 플러그인은 babel이 코드를 transpile하는 규칙들이다
yarn add -D @babel/plugin-transform-arrow-functions
yarn babel src --out-dir lib --plugins=@babel/plugin-transform-arrow-functionsmodule.exports = {
plugins: [
'@babel/plugin-transform-block-scoping',
'@babel/plugin-transform-arrow-functions',
],
};필요한 플러그인들을 모아서 프리셋으로 묶어놓자!
function mypreset() {
return {
plugins: [
"@babel/plugin-transform-arrow-functions",
"@babel/plugin-transform-block-scoping",
"@babel/plugin-transform-strict-mode",
],
}
}
module.exports = {
presets: [
mypreset(),
],
};바벨 공식 프리셋이 4가지 있다
preset-env
preset-typescript
// babel.config.js
module.exports = {
presets: [
[
"@babel/preset-env",
{
targets: {
chrome: "79", // 크롬 79까지 지원하는 코드를 만든다
ie: "11", // ie 11까지 지원하는 코드를 만든다
node: 'current',
},
},
],
],
}promise는 간단한 스코핑 대체로 해결될 문제가 아니다
// babel.config.js:
module.exports = {
presets: [
[
"@babel/preset-env",
{
useBuiltIns: "usage", // 폴리필 사용 방식 지정, usage, entry, false(default)
corejs: {
// 폴리필 버전 지정
version: 2,
},
},
],
],
}