Sucrase is a super-fast alternative to Babel

June 29, 2018 0 Comments

Sucrase is a super-fast alternative to Babel



Originally I shared this material to Syndicode blog

Working with Babel? Sure, it's great! But don't you want to skip these steps of tokenizing the input source code into a token stream and walking the AST to compute the scope information for each variable? If you could work on a lower level and use a custom parser for its use case, you could be much faster! But look what I have found... Sucrase is a super-fast alternative to Babel!

As JavaScript implementations mature, you don't want Babel transforms in development when you know that you're targeting a modern runtime. How to speed up the build step? If you're using non-standard language extensions like JSX, TypeScript, or Flow it's impossible to disable Babel entirely. And disabling most transforms in Babel doesn't speed it up as much as you expect.

Sucrase bypasses most of the steps that Babel takes. And works like this:

  1. Tokenize the input source code into a token stream using a trimmed-down fork of the Babel parser. This fork produces meaningful token metadata specifically designed for the later transforms.
  2. Scan through the tokens, computing preliminary information like all imported/exported names.
  3. Run the transform by doing a pass through the tokens and performing a number of careful find-and-replace operations.

Because Sucrase works on a lower level and uses a custom parser for its use case, it is much faster than Babel.

Note! Sucrase is intended to be useful for the most common cases, but it does not aim to have nearly the scope and versatility of Babel. Examples about Sucrase:

  • No checking for code errors. Give it valid code, and it will produce valid JS code.
  • It is not good for prototyping language extensions and upcoming language features. Its faster architecture makes new transforms more difficult to write and more fragile.
  • It will never produce code for old browsers like IE.
  • It is hesitant to implement upcoming JS features, although some of them make sense to implement for pragmatic reasons. Its main focus is on JSX, TypeScript, Flow language extensions that will never be supported by JS runtimes.
  • Like Babel, Sucrase is not a typechecker, and must process each file in isolation.
  • Sucrase is mostly beneficial in development, and in many cases, Babel will be more suitable for production builds.

Check it out on GitHub or go to Sucrase official site!

Tag cloud