API" class="reference-link">API

Babel is actually a collection of modules. In this section we’ll walk through the major ones, explaining what they do and how to use them.

Note: This is not a replacement for detailed API documentation, which is available here.

babel-parser" class="reference-link">babel-parser

Started as a fork of Acorn, the Babel Parser is fast, simple to use, has plugin-based architecture for non-standard features (as well as future standards).

First, let’s install it.

  1. $ npm install --save @babel/parser

Let’s start by simply parsing a string of code:

  1. import parser from "@babel/parser";
  2. const code = `function square(n) {
  3. return n * n;
  4. }`;
  5. parser.parse(code);
  6. // Node {
  7. // type: "File",
  8. // start: 0,
  9. // end: 38,
  10. // loc: SourceLocation {...},
  11. // program: Node {...},
  12. // comments: [],
  13. // tokens: [...]
  14. // }

We can also pass options to parse() like so:

  1. parser.parse(code, {
  2. sourceType: "module", // default: "script"
  3. plugins: ["jsx"] // default: []
  4. });

sourceType can either be "module" or "script" which is the mode that the Babel Parser should parse in. "module" will parse in strict mode and allow module declarations, "script" will not.

Note: sourceType defaults to "script" and will error when it finds import or export. Pass sourceType: "module" to get rid of these errors.

Since the Babel Parser is built with a plugin-based architecture, there is also a plugins option which will enable the internal plugins. Note that the Babel Parser has not yet opened this API to external plugins, although may do so in the future.

To see a full list of plugins, see the Babel parser docs.

babel-traverse" class="reference-link">babel-traverse

The Babel Traverse module maintains the overall tree state, and is responsible for replacing, removing, and adding nodes.

Install it by running:

  1. $ npm install --save @babel/traverse

We can use it alongside to traverse and update nodes:

  1. import parser from "@babel/parser";
  2. import traverse from "@babel/traverse";
  3. const code = `function square(n) {
  4. return n * n;
  5. }`;
  6. const ast = parser.parse(code);
  7. traverse(ast, {
  8. enter(path) {
  9. if (
  10. path.node.type === "Identifier" &&
  11. path.node.name === "n"
  12. ) {
  13. path.node.name = "x";
  14. }
  15. }
  16. });

babel-types" class="reference-link">babel-types

Babel Types is a Lodash-esque utility library for AST nodes. It contains methods for building, validating, and converting AST nodes. It’s useful for cleaning up AST logic with well thought out utility methods.

You can install it by running:

  1. $ npm install --save @babel/types

Then start using it:

  1. import traverse from "@babel/traverse";
  2. import * as t from "@babel/types";
  3. traverse(ast, {
  4. enter(path) {
  5. if (t.isIdentifier(path.node, { name: "n" })) {
  6. path.node.name = "x";
  7. }
  8. }
  9. });

Definitions" class="reference-link">Definitions

Babel Types has definitions for every single type of node, with information on what properties belong where, what values are valid, how to build that node, how the node should be traversed, and aliases of the Node.

A single node type definition looks like this:

  1. defineType("BinaryExpression", {
  2. builder: ["operator", "left", "right"],
  3. fields: {
  4. operator: {
  5. validate: assertValueType("string")
  6. },
  7. left: {
  8. validate: assertNodeType("Expression")
  9. },
  10. right: {
  11. validate: assertNodeType("Expression")
  12. }
  13. },
  14. visitor: ["left", "right"],
  15. aliases: ["Binary", "Expression"]
  16. });

Builders" class="reference-link">Builders

You’ll notice the above definition for BinaryExpression has a field for a builder.

  1. builder: ["operator", "left", "right"]

This is because each node type gets a builder method, which when used looks like this:

  1. t.binaryExpression("*", t.identifier("a"), t.identifier("b"));

Which creates an AST like this:

  1. {
  2. type: "BinaryExpression",
  3. operator: "*",
  4. left: {
  5. type: "Identifier",
  6. name: "a"
  7. },
  8. right: {
  9. type: "Identifier",
  10. name: "b"
  11. }
  12. }

Which when printed looks like this:

  1. a * b

Builders will also validate the nodes they are creating and throw descriptive errors if used improperly. Which leads into the next type of method.

Validators" class="reference-link">Validators

The definition for BinaryExpression also includes information on the fields of a node and how to validate them.

  1. fields: {
  2. operator: {
  3. validate: assertValueType("string")
  4. },
  5. left: {
  6. validate: assertNodeType("Expression")
  7. },
  8. right: {
  9. validate: assertNodeType("Expression")
  10. }
  11. }

This is used to create two types of validating methods. The first of which is isX.

  1. t.isBinaryExpression(maybeBinaryExpressionNode);

This tests to make sure that the node is a binary expression, but you can also pass a second parameter to ensure that the node contains certain properties and values.

  1. t.isBinaryExpression(maybeBinaryExpressionNode, { operator: "*" });

There is also the more, ehem, assertive version of these methods, which will throw errors instead of returning true or false.

  1. t.assertBinaryExpression(maybeBinaryExpressionNode);
  2. t.assertBinaryExpression(maybeBinaryExpressionNode, { operator: "*" });
  3. // Error: Expected type "BinaryExpression" with option { "operator": "*" }

Converters" class="reference-link">Converters

[WIP]

babel-generator" class="reference-link">babel-generator

Babel Generator is the code generator for Babel. It takes an AST and turns it into code with sourcemaps.

Run the following to install it:

  1. $ npm install --save @babel/generator

Then use it

  1. import parser from "@babel/parser";
  2. import generate from "@babel/generator";
  3. const code = `function square(n) {
  4. return n * n;
  5. }`;
  6. const ast = parser.parse(code);
  7. generate(ast, {}, code);
  8. // {
  9. // code: "...",
  10. // map: "..."
  11. // }

You can also pass options to generate().

  1. generate(ast, {
  2. retainLines: false,
  3. compact: "auto",
  4. concise: false,
  5. quotes: "double",
  6. // ...
  7. }, code);

babel-template" class="reference-link">babel-template

Babel Template is another tiny but incredibly useful module. It allows you to write strings of code with placeholders that you can use instead of manually building up a massive AST. In computer science, this capability is called quasiquotes.

  1. $ npm install --save @babel/template
  1. import template from "@babel/template";
  2. import generate from "@babel/generator";
  3. import * as t from "@babel/types";
  4. const buildRequire = template(`
  5. var IMPORT_NAME = require(SOURCE);
  6. `);
  7. const ast = buildRequire({
  8. IMPORT_NAME: t.identifier("myModule"),
  9. SOURCE: t.stringLiteral("my-module")
  10. });
  11. console.log(generate(ast).code);
  1. var myModule = require("my-module");