Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tại sao cần Babel JS?

Babel là toolchain chuyển mã **ECMAScript 2015+ (ES6+)** sang phiên bản **backward-compatible** chạy được trên trình duyệt cũ/môi trường cũ.

3 lý do chính dùng Babel

  • Syntax transformation: Viết syntax mới (optional chaining ?., nullish coalescing ??, class fields, top-level await...) — Babel compile xuống ES5/ES2015.
  • Polyfill missing features: Cung cấp polyfill cho API mới (Promise, Array.prototype.flat, Object.fromEntries...) qua @babel/preset-env + core-js (chỉ polyfill những gì target browser thiếu).
  • Source code transformations: JSX (React), TypeScript/Flow type stripping, custom macros, minification...

Quy trình

  1. Parse → AST
  2. Transform qua plugins/presets
  3. Generate code target

Kết luận: Babel cho phép dev dùng JS modern ngay hôm nay mà không lo browser support.