Sucrase
Super-fast alternative to Babel for when you can target modern JS runtimes
Install / Use
/learn @alangpierce/SucraseREADME
Sucrase
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:
- jsx: Enables JSX syntax. By default, JSX is transformed to
React.createClass, but may be preserved or transformed to_jsx()by setting thejsxRuntimeoption. Also addscreateReactClassdisplay names and JSX context information. - typescript: Compiles TypeScript code to JavaScript, removing type
annotations and handling features like enums. Does not check types. Sucrase
transforms each file independently, so you should enable the
isolatedModulesTypeScript flag so that the typechecker will disallow the few features likeconst enums that need cross-file compilation. The Sucrase optionkeepUnusedImportscan be used to disable all automatic removal of imports and exports, analogous to TSverbatimModuleSyntax. - flow: Removes Flow type annotations. Does not check types.
- imports: Transforms ES Modules (
import/export) to CommonJS (require/module.exports) using the same approach as Babel and TypeScript with--esModuleInterop. IfpreserveDynamicImportis specified in the Sucrase options, then dynamicimportexpressions are left alone, which is particularly useful in Node to load ESM-only libraries. IfpreserveDynamicImportis not specified,importexpressions are transformed into a promise-wrapped call torequire. - react-hot-loader: Performs the equivalent of the
react-hot-loader/babeltransform in the react-hot-loader project. This enables advanced hot reloading use cases such as editing of bound methods. - jest: Hoist desired jest method calls above imports in
the same way as babel-plugin-jest-hoist.
Does not validate the arguments passed to
jest.mock, but the same rules still apply.
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:
- Optional chaining:
a?.b - Nullish coalescing:
a ?? b - Class fields:
class C { x = 1; }. This includes static fields but not the#xprivate field syntax. - Numeric separators:
const n = 1_234; - Optional catch binding:
try { doThing(); } catch { }.
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:
- Decorators, private fields,
throwexpressions, generator arrow functions, anddoexpressions are all unsupported in browsers and Node (as of this writing), and Sucrase doesn't make an attempt to transpile them. - Object rest/spread, async functions, and async iterators are all recent features that should work fine, but might cause issues if you use older versions of tools like webpack. BigInt and newer regex features may or may not work, based on your tooling.
JSX Options
By default, JSX is compiled to React functions in development mode. This can be configured with a few options:
- jsxRuntime: A string specifying the transform mode, which can be one of three values:
"classic"(default): The original JSX transform that callsReact.createElementby default. To configure for non-React use cases, specify:- jsxPragma: Element creation function, defaults to
React.createElement. - jsxFragmentPragma: Fragment component, defaults to
React.Fragment.
- jsxPragma: Element creation function, defaults to
"automatic": The new JSX transform introduced with React 17, which callsjsxfunctions and auto-adds import statements. To configure for non-React use cases, specify:- jsxImportSource: Package name for auto-generated import statements, defaults to
react.
- jsxImportSource: Package name for auto-generated import statements, defaults to
"preserve": Don't transform JSX, and instead emit it as-is in the output code.
- production: If
true, use production version of functions and don't include debugging information. When using React in production mode with the automatic transform, this must be set to true to avoid an error aboutjsxDEVbeing missing.
Legacy CommonJS interop
Two legacy modes can be used with the imports transform:
- enableLegacyTypeScriptModuleInterop: Use the default TypeScript approach
to CommonJS interop instead of assuming that TypeScript's
--esModuleInteropflag is enabled. For example, if a CJS module exports a function, legacy TypeScript interop requires you to writeimport * as add from './add';, while Babel, Webpack, Node.js, and TypeScript with--esModuleInteroprequire you to writeimport add from './add';. As mentioned in the docs, the TypeScript team recommends you always use--esModuleInterop. - enableLegacyBabel5ModuleInterop: Use the Babel 5 approach to CommonJS
interop, so that you can run
require('./MyModule')instead ofrequire('./MyModule').default. Analogous to babel-plugin-add-module-exports.
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
Related Skills
node-connect
342.0kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
84.7kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
Writing Hookify Rules
84.7kThis skill should be used when the user asks to "create a hookify rule", "write a hook rule", "configure hookify", "add a hookify rule", or needs guidance on hookify rule syntax and patterns.
review-duplication
99.6kUse this skill during code reviews to proactively investigate the codebase for duplicated functionality, reinvented wheels, or failure to reuse existing project best practices and shared utilities.
