Home

Awesome

Sucrase

Build Status npm version Install Size MIT License Join the chat at https://gitter.im/sucrasejs

Try it out

Quick usage

yarn add --dev sucrase  # Or npm install --save-dev sucrase
node -r sucrase/register main.ts

Using the ts-node integration:

yarn add --dev sucrase ts-node typescript
./node_modules/.bin/ts-node --transpiler sucrase/ts-node-plugin main.ts

Project overview

Sucrase is an alternative to Babel that allows super-fast development builds. Instead of compiling a large range of JS features to be able to work in Internet Explorer, Sucrase assumes that you're developing with a recent browser or recent Node.js version, so it focuses on compiling non-standard language extensions: JSX, TypeScript, and Flow. Because of this smaller scope, Sucrase can get away with an architecture that is much more performant but less extensible and maintainable. Sucrase's parser is forked from Babel's parser (so Sucrase is indebted to Babel and wouldn't be possible without it) and trims it down to a focused subset of what Babel solves. If it fits your use case, hopefully Sucrase can speed up your development experience!

Sucrase has been extensively tested. It can successfully build the Benchling frontend code, Babel, React, TSLint, Apollo client, and decaffeinate with all tests passing, about 1 million lines of code total.

Sucrase is about 20x faster than Babel. Here's one measurement of how Sucrase compares with other tools when compiling the Jest codebase 3 times, about 360k lines of code total:

            Time            Speed
Sucrase     0.57 seconds    636975 lines per second
swc         1.19 seconds    304526 lines per second
esbuild     1.45 seconds    248692 lines per second
TypeScript  8.98 seconds    40240 lines per second
Babel       9.18 seconds    39366 lines per second

Details: Measured on July 2022. Tools run in single-threaded mode without warm-up. See the benchmark code for methodology and caveats.

Transforms

The main configuration option in Sucrase is an array of transform names. These transforms are available:

When the imports transform is not specified (i.e. when targeting ESM), the injectCreateRequireForImportRequire option can be specified to transform TS import foo = require("foo"); in a way that matches the TypeScript 4.7 behavior with module: nodenext.

These newer JS features are transformed by default:

If your target runtime supports these features, you can specify disableESTransforms: true so that Sucrase preserves the syntax rather than trying to transform it. Note that transpiled and standard class fields behave slightly differently; see the TypeScript 3.7 release notes for details. If you use TypeScript, you can enable the TypeScript option useDefineForClassFields to enable error checking related to these differences.

Unsupported syntax

All JS syntax not mentioned above will "pass through" and needs to be supported by your JS runtime. For example:

JSX Options

By default, JSX is compiled to React functions in development mode. This can be configured with a few options:

Legacy CommonJS interop

Two legacy modes can be used with the imports transform:

Usage

Tool integrations

Usage in Node

The most robust way is to use the Sucrase plugin for ts-node, which has various Node integrations and configures Sucrase via tsconfig.json:

ts-node --transpiler sucrase/ts-node-plugin

For projects that don't target ESM, Sucrase also has a require hook with some reasonable defaults that can be accessed in a few ways:

Options can be passed to the require hook via a SUCRASE_OPTIONS environment variable holding a JSON string of options.

Compiling a project to JS

For simple use cases, Sucrase comes with a sucrase CLI that mirrors your directory structure to an output directory:

sucrase ./srcDir -d ./outDir --transforms typescript,imports

Usage from code

For any advanced use cases, Sucrase can be called from JS directly:

import {transform} from "sucrase";
const compiledCode = transform(code, {transforms: ["typescript", "imports"]}).code;

What Sucrase is not

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. Some specific examples:

See the Project Vision document for more details on the philosophy behind Sucrase.

Motivation

As JavaScript implementations mature, it becomes more and more reasonable to disable Babel transforms, especially in development when you know that you're targeting a modern runtime. You might hope that you could simplify and speed up the build step by eventually disabling Babel entirely, but this isn't possible if you're using a non-standard language extension like JSX, TypeScript, or Flow. Unfortunately, disabling most transforms in Babel doesn't speed it up as much as you might expect. To understand, let's take a look at how Babel works:

  1. Tokenize the input source code into a token stream.
  2. Parse the token stream into an AST.
  3. Walk the AST to compute the scope information for each variable.
  4. Apply all transform plugins in a single traversal, resulting in a new AST.
  5. Print the resulting AST.

Only step 4 gets faster when disabling plugins, so there's always a fixed cost to running Babel regardless of how many transforms are enabled.

Sucrase bypasses most of these steps, 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 does not produce a full AST, but still 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, like replacing <Foo with React.createElement(Foo.

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

Contributing

Contributions are welcome, whether they be bug reports, PRs, docs, tests, or anything else! Please take a look through the Contributing Guide to learn how to get started.

License and attribution

Sucrase is MIT-licensed. A large part of Sucrase is based on a fork of the Babel parser, which is also MIT-licensed.

Why the name?

Sucrase is an enzyme that processes sugar. Get it?