Post

Babel과 Polyfill

What is Babel?

  • Babel is a JavaScript compiler.
  • ES6 문법을 구식 브라우저에서도 돌아가는 하위호환 문법으로 트랜스파일 해주는 트랜스파일러. 또는 컴파일러.
  • https://babeljs.io/docs/기타 jsx변환이나 type 변환에 대한 상세한 내용은 공식 docs 참고.

What is Polyfill?

  • 문법에 대한 하위호환 지원은 babel이 하고, API에 대한 하위호환 지원은 Polyfill이 담당.
  • 즉 ES5에 존재하지 않는 Promise 같은 객체를 구형 브라우저에서도 사용 할 수 있게, 해당 객체들을 정의해주는 역할.
1
2
3
Promise = Promise ?? /* 자체 구현 Promise */;
Object.entries = Object.entries ?? /* 자체 구현 */

Babel과 Polyfill 어떻게 세팅하는게 좋은가?

1. 전역스코프에 polyfill 추가하는 방식

단일 app이나 CLI라면 괜찮은 방식. library라면 전역 오염 없는 2방식을 고려해보는게 좋다.

https://babeljs.io/docs/babel-plugin-transform-runtime#why

1-1. @babel/polyfill 직접 사용하는 방식 (deprecated)
1
2
3
package.json에 dependency "@babel/polyfill" 추가
index.js에 import "@babel/polyfill" 추가

https://babeljs.io/docs/babel-polyfill

1-2. import core-js 하는 방식
1
2
3
4
index.js에 추가
import 'core-js/stable';
import 'regenerator-runtime/runtime';

1-3. babel config의 preset 사용하기

2. @babel/plugin-transform-runtime & core-js@3 사용해 전역 오염 없이 polyfill 하는 방식

browserslist

참고

babel config 적용 순서

https://babeljs.io/docs/configuration

1
2
babel.config.json < .babelrc < programmatic options from @babel/cli

디버깅
1
2
3
$ BABEL_SHOW_CONFIG_FOR=./src/index.js npm run build:local
config가 2번 적용되고 있는지, 최종적으로 합쳐져 적용된 설정들은 어떻게 되는지를 볼 수 있다.

This post is licensed under CC BY 4.0 by the author.