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

Babel là gì? Nó giúp viết JavaScript như thế nào?

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ũ.

Tại sao cần Babel?

  • Syntax transformation: Dùng syntax mới (optional chaining, nullish coalescing, class fields, top-level await...) mà không lo browser support.
  • Polyfill: Cung cấp polyfill cho API mới (Promise, Array.flat, Object.fromEntries...) qua @babel/preset-env + core-js.
  • Source code transformation: JSX (React), Flow/TypeScript strip types, custom macros...

Cách hoạt động

  1. Parse source code → AST (Abstract Syntax Tree).
  2. Transform AST qua plugins/presets.
  3. Generate code ES5/ES2015 target.

Cấu hình phổ biến

// babel.config.js
module.exports = {
  presets: [
    ['@babel/preset-env', { targets: "> 0.25%, not dead" }],
    '@babel/preset-react',
    '@babel/preset-typescript'
  ]
};

Kết quả: Viết code modern, Babel lo phần compatibility.