Babel Documentation

repository·main·Indexed 20 days ago

https://github.com/babel/website

Official documentation for the Babel ecosystem, including guides on the Babel CLI, compiler assumptions for optimization, polyfill requirements, and handling browser caveats for Internet Explorer. It also provides instructions for contributing to and running the babeljs.io website locally using Docusaurus, Node.js, and Yarn.

Tokens
207.7K
Snippets
1.3K
Records
1.5K
Agent score
73%

What's inside Babel

  1. What is Babel?

    main

    Babel is a JavaScript compiler toolchain used to convert ECMAScript 2015+ code into backwards-compatible versions of JavaScript for older browsers or environments.

    Key capabilities include:

    • Syntax Transformation: Converting new syntax (like arrow functions) into older syntax (like ES5 functions).
    • Polyfilling: Adding missing features to target environments via third-party libraries like core-js.
    • Codemods: Performing source code transformations.
    • JSX Support: Converting JSX syntax into standard JavaScript.
    • Type Annotation Stripping: Removing Flow or TypeScript annotations to produce valid JavaScript.
    // Babel Input: ES2015 arrow function
    [1, 2, 3].map(n => n + 1);
    
    // Babel Output: ES5 equivalent
    [1, 2, 3].map(function(n) {
      return n + 1;
    });
  2. Overview of @babel/parser

    main
    The @babel/parser (formerly known as Babylon) is a JavaScript parser used within the Babel ecosystem. It supports the latest ECMAScript versions (defaulting to ES2020), comment attachment, and various syntax extensions including JSX, Flow, and TypeScript. It also supports experimental language proposals (up to stage-0).
  3. Capabilities of babel-helper-evaluate-path

    main

    The babel-helper-evaluate-path utility is designed to analyze variable usage and scope within JavaScript code. It provides the following detection capabilities:

    1. Detect usages before initialization or declaration: It can identify when a variable is accessed before it is formally initialized (e.g., identifying a ReferenceError for let bindings) or when it is accessed during its hoisting period (e.g., identifying that a var binding is void 0).

    2. Detect usages in scopes outside of initialization for hoisted variables: It can analyze if a variable declared with var is being used in a scope where its value cannot be determined due to conditional initialization (e.g., inside an if block).

    Example: Detection of initialization/declaration issues

    function foo() {
      console.log(b); // ReferenceError
      let b = 1;
    }
    
    function bar() {
      console.log(a); // a is void 0
      var a = 5;
      console.log(a); // 5
    }

    Example: Detection of hoisted variable usage in conditional scopes

    function foo() {
      if (a) var x = 5;
      console.log(x); // cannot determine
    }
    function foo() {
      console.log(b); // ReferenceError
      let b = 1;
    }
    
    function bar() {
      console.log(a); // a is void 0
      var a = 5;
      console.log(a); // 5
    }
    
    function foo() {
      if (a) var x = 5;
      console.log(x); // cannot determine
    }
  4. Identify Babel's core packages and their purposes

    main

    Babel is composed of several specialized packages that handle different stages of the transformation process. Depending on your needs (parsing, generating code, or integrating with the transform API), you may need to use specific modules:

    • babel-parser (Babylon): A JavaScript parser used to convert source code into an Abstract Syntax Tree (AST).
    • babel-core: The central module that wraps the transform API; typically used when building integrations.
    • babel-generator: Converts an AST back into a string of code.
    • babel-types: A utility library (similar to Lodash) for working with and validating AST nodes.
    • babel-register: A Node.js require hook that automatically compiles files on the fly when they are required.
    • babel-template: Allows you to generate an AST from a string template.
    • babel-helpers: A collection of helper functions utilized by various Babel transforms.
    • babel-code-frame: A utility to generate error messages that include a visual code frame pointing to specific source locations.
  5. Use @babel/plugin-transform-react-jsx-development

    main

    This plugin is a developer-focused version of @babel/plugin-transform-react-jsx. It provides enhanced validation error messages and precise code location information (file name, line number, column number) for debugging React applications.

    Warning: This plugin is intended for development environments only, as it generates significantly more output than a production build.

  6. Overview of @babel/types

    main

    The @babel/types module provides a utility suite for working with Abstract Syntax Trees (ASTs). It is primarily used for two purposes:

    1. Building ASTs: Methods to programmatically construct new AST nodes.
    2. Type Checking: Methods to validate the type of an existing AST node (e.g., checking if a node is an Identifier or a FunctionDeclaration).
  7. What is Babili and why use it instead of Uglify?

    main

    Babili (also known as babel-minify) is an ES2015+ aware minifier built using the Babel toolchain.

    Key Advantages:

    • ES2015+ Support: Unlike older minifiers (like Uglify) that require code to be transpiled down to ES5 before minification, Babili can parse and minify modern ECMAScript directly. This allows you to ship smaller, more optimized ES2015+ code to modern browsers.
    • Modular Architecture: Because it is a Babel preset, it is composed of individual plugins (e.g., babel-plugin-minify-constant-folding, babel-plugin-minify-mangle-names). This makes it highly customizable and allows for easy contribution of new optimization strategies.
    • Toolchain Integration: It works seamlessly with existing Babel configurations, presets, and plugins.

    Comparison Summary

    FeatureUglifyBabili
    ES2015+ SupportLimited (requires ES5 transpilation)Native (ES2015+ aware)
    ExtensibilityLow (custom parser/tooling)High (Babel plugin system)
    MaturityBattle-tested/Production readyEarly stage/Beta
    PerformanceVery fast/Small outputImproving (currently slower than Uglify)
  8. Implement new TC39 proposals in Babel

    main

    Babel tracks and implements TC39 proposals. Current status:

    • Stage 3: Babel can parse all Stage 3 proposals and transform most of them. Exceptions include top-level await, import assertions, and JSON modules (which are typically handled by bundlers).
    • Stage 2: Babel supports most Stage 2 proposals, with ongoing work to implement the new iteration of decorators and transforms for Module Blocks.
    • Stage 1: Babel provides updates for proposals like the pipeline operator and do expressions as they evolve.
  9. Understand TypeScript transformation caveats in Babel

    main

    When using @babel/plugin-transform-typescript, be aware of several fundamental differences between Babel and the TypeScript compiler (tsc):

    1. No Type-Checking: Babel does not perform type-checking. Code that is syntactically valid but fails TypeScript type-checking may be transformed in unexpected or invalid ways.
    2. isolatedModules Behavior: Babel does not read your tsconfig.json. The transformation process always behaves as if isolatedModules is enabled. You must use Babel-native options to configure behavior that you would typically set in tsconfig.json.
    3. Export Restrictions: Babel does not allow exporting var or let from modules. This is because the TypeScript compiler's ability to handle these depends on a type-model (to determine if a variable is mutated) which Babel does not have.

    Workaround for var/let exports: Use const. If mutation is required, use an object with internal mutability instead of exporting a mutable variable.

  10. Manage Babel helpers with `@babel/runtime`

    main

    Babel uses helper functions (like _classCallCheck) to implement features in older environments. To avoid duplicating these helpers in every file and to reduce bundle size, use @babel/plugin-transform-runtime along with @babel/runtime as a dependency. This allows Babel to require the helpers from a central module instead of inlining them.

    // Instead of inlining the helper, it is required from the runtime
    var _classCallCheck = require("@babel/runtime/helpers/classCallCheck");
    
    var Person = function Person() {
      _classCallCheck(this, Person);
    };
  11. Transform RegExp constructors to RegExp literals

    main

    The babel-plugin-transform-regexp-constructors plugin converts new RegExp() constructor calls into static RegExp literals where possible. This can lead to more concise code and potentially better optimization by engines.

    // In
    const foo = "ab+";
    var a = new RegExp(foo + "c", "i");
    
    // Out
    const foo = "ab+";
    var a = /ab+c/i;