Skip to content

alangpierce/sucrase

main
Switch branches/tags
Code

Latest commit

Instructions: https://github.com/alangpierce/sucrase/wiki/Porting-changes-from-Babel's-parser

976bfbbf69 fix: assure left bracket is not consumed after dot (#13695)
🚫 Bug doesn't seem to apply to Sucrase, and fix is validation only.

1d4bd31950 add missing ExportNamespaceSpecifier in spec.md (#13691)
🚫 Docs only.

b141c85b17 fix(babel-parser): delete `static` property from class static block for TS (#13680)
🚫 Only affects AST.

64d116bd6a fix(parser): [Babel8] Align error codes between Flow and TypeScript (#13294)
🚫 Only affects error reporting.

a54f041440 test(parser): add no_plugin tests for module blocks (#13714)
🚫 Test only.

b2376757d7 v7.15.4
🚫 Release only.

44388e6e81 Disallow `#a in #b in c` and similar expressions (#13727)
🚫 Only affects validation.

e82e43ca33 v7.15.5
🚫 Release only.

62e42a3f60 fix(babel-parser): Fix end of `range` of `SequenceExpression` (#13731)
🚫 AST only.

c25ec3e069 [babel-parser] add tests for static blocks with line breaks (#13734)
 Added similar test for Sucrase (though nothing was broken).

3c3f5205c9 Fix right precedence of Hack pipes (#13668)
 Given the active spec work, I filed #674 to revisit in the future.

34a27e46f8 v7.15.6
🚫 Release only.

710b3919fa [estree] Fix conversion of `PrivateName` in `MemberExpression` (#13755)
🚫 Only affects estree.

da79c90f2a fix(babel-parser): Allow line break before `assert` return type (#13771)
 Ported fix.

d2076a531f Store token type as number (#13768)
🚫 Optimization that's pretty much already in Sucrase.

8d0294edf8 v7.15.7
🚫 Release only.

2e2d202694 [babel 8] Materialize ESTree's `classFeatures` option (#13752)
🚫 Not relevant for Sucrase.

178d43ff17 Tokenize keywords-like identifier as new tokens (#13769)
🚫 Interesting alternative approach to Sucrase's contextual keyword enums. Doesn't seem worth it to switch to Babel's approach for now.

64f14b05fa Collect comments around parentheses in expressions (#13803)
🚫 AST only.

c4b13725aa v7.15.8
🚫 Release only.

b5907ef967 remove executable permission from files that shouldn't have it (#13873)
🚫 Babel-internal change.

62b2c5ebb9 Regenerate parser fixtures (#13882)
🚫 Babel-internal change.

c7ddb1ae93 Use `workspace:^` to specify `@babel/` dependencies (#13772)
🚫 Babel-internal change.

fb7ddf4d38 [ts] Support private methods overloads (#13876)
🚫 Issue doesn't affect Sucrase.

ddc45a5a50 Enable class static blocks by default (#13713)
🚫 Already enabled by default for Sucrase.

ad59a2c618 Caret topic (pipe operator) (#13749)
🚫 Not implementing topic token changes for now until it's finalized, see #674

718c6cb7de Handle `.mts` and `.cts` files in `@babel/preset-typescript` (#13838)
🚫 Only adds error handling to the parser. Sucrase integrations should better handle .mts and .cts, but that can be done in follow-up work.

872086a9a0 feat: support `startColumn` option (#13887)
🚫 Not relevant to Sucrase.

d5ba355867 Support TypeScript 4.5 type-only import/export specifiers (#13802)
 Implemented separately as #713

45308f3cba v7.16.0
🚫 Release only.

cba7f9e503 Add missing assertions type (#13905)
🚫 AST only.

68fad796b1 v7.16.2
🚫 Release only.

1fa759f989 refactor: extract tt.lt and tt.gt from tt.relation (#13892)
🚫 Already done in Sucrase. Also includes a refactor that could be reasonable to incorporate, but I'll skip that for now.

7250d2562b Simplifiy tracking of valid JSX positions (#13891)
🚫 The relevant code has changed enough that this probably isn't worth porting.

a6a526968d fix: incorrect await rejection following arrow function in parameters (#13928)
🚫 Bug fix is in code not relevant to Sucrase.

3b6f061e18 v7.16.3
🚫 Release only.

135ab837bc Throw on duplicate `__proto__` props followed by assignment (#13951)
🚫 Only affects error handling.

54c539ecc1 Refactor bindingProperty parsing (#13929)
🚫 Nothing stands out as relevant to Sucrase.

966387d263 Always expose `expressionValue` in `DirectiveLiteral` nodes (#13960)
🚫 AST only.

87fc2e76d7 Add `assertions` to `ExportNamedDeclaration` without `from` (#13957)
🚫 AST only.

99774ee9fa v7.16.4
🚫 Release only.

d30308fe8e fix: update UnexpectedPrivateField error message (#13975)
🚫 Validation only.

a470f7b479 Recover from shorthand assign exprs (#13968)
 We already handled this case, but I added a test to confirm.

75996cb62b Use full import specifier path in tests (#13938)
🚫 Babel-internal change.

ad1798ed48 Only bundle the release build, and don't import `src` in tests (#13978)
🚫 Babel-internal change.

f4236f43a1 Extend `hasPlugin` to accept plugin-configuration array pairs (#13982)
🚫 Sucrase uses a different config system.

2d989a983d Run tests in a native Node.js ESM environment (#13966)
🚫 Babel-internal change. (Though very cool to see!)

94af0e5c62 Improve template tokenizing (#13919)
🚫 Sucrase got rid of context, so it looks like this change isn't as relevant.

39080492f4 maintain estree string literal shape when cloned (#14039)
🚫 AST only.

7b7ab94066 v7.16.5
🚫 Release only.

7794201940 fix: handle tokens for invalid template element (#14055)
🚫 Bug not relevant to Sucrase.

5687ade5e7 v7.16.6
🚫 Release only.

ad17fe1cce fix: check preceding line break before exclamation (#14049)
 Fixed bug in the same way and added a test.

d1cabf6bc8 [babel 8] Add `"exports"` to every package (#14013)
🚫 Babel-internal change.

23e884048a v7.16.7
🚫 Release only.
00a86a2

Git stats

Files

Permalink
Failed to load latest commit information.
Type
Name
Latest commit message
Commit time
Apr 6, 2022
Jul 1, 2022
Jul 1, 2022
Jul 1, 2022
Jul 1, 2022

Sucrase

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

Try it out

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     1.64 seconds    220221 lines per second
swc         2.13 seconds    169502 lines per second
esbuild     3.02 seconds    119738 lines per second
TypeScript  24.18 seconds   14937 lines per second
Babel       27.22 seconds   13270 lines per second

Details: Measured on January 2021. 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: Transforms JSX syntax to React.createElement, e.g. <div a={b} /> becomes React.createElement('div', {a: b}). Behaves like Babel 7's React preset, including adding createReactClass display 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 isolatedModules TypeScript flag so that the typechecker will disallow the few features like const enums that need cross-file compilation.
  • 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. Also includes dynamic import.
  • react-hot-loader: Performs the equivalent of the react-hot-loader/babel transform 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.

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:

  • Decorators, private fields, throw expressions, generator arrow functions, and do expressions 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

Like Babel, Sucrase compiles JSX to React functions by default, but can be configured for any JSX use case.

  • jsxPragma: Element creation function, defaults to React.createElement.
  • jsxFragmentPragma: Fragment component, defaults to React.Fragment.

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 --esModuleInterop flag is enabled. For example, if a CJS module exports a function, legacy TypeScript interop requires you to write import * as add from './add';, while Babel, Webpack, Node.js, and TypeScript with --esModuleInterop require you to write import 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 of require('./MyModule').default. Analogous to babel-plugin-add-module-exports.

Usage

Installation:

yarn add --dev sucrase  # Or npm install --save-dev sucrase

Often, you'll want to use one of the build tool integrations: Webpack, Gulp, Jest, Rollup, Broccoli.

Compile on-the-fly via a require hook with some reasonable defaults:

// Register just one extension.
require("sucrase/register/ts");
// Or register all at once.
require("sucrase/register");

Compile on-the-fly via a drop-in replacement for node:

sucrase-node index.ts

Run on a directory:

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

Call 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:

  • Sucrase does not check your code for errors. Sucrase's contract is that if you give it valid code, it will produce valid JS code. If you give it invalid code, it might produce invalid code, it might produce valid code, or it might give an error. Always use Sucrase with a linter or typechecker, which is more suited for error-checking.
  • Sucrase is not pluginizable. With the current architecture, transforms need to be explicitly written to cooperate with each other, so each additional transform takes significant extra work.
  • Sucrase is not good for prototyping language extensions and upcoming language features. Its faster architecture makes new transforms more difficult to write and more fragile.
  • Sucrase will never produce code for old browsers like IE. Compiling code down to ES5 is much more complicated than any transformation that Sucrase needs to do.
  • Sucrase is hesitant to implement upcoming JS features, although some of them make sense to implement for pragmatic reasons. Its main focus is on language extensions (JSX, TypeScript, Flow) that will never be supported by JS runtimes.
  • Like Babel, Sucrase is not a typechecker, and must process each file in isolation. For example, TypeScript const enums are treated as regular enums rather than inlining across files.
  • You should think carefully before using Sucrase in production. Sucrase is mostly beneficial in development, and in many cases, Babel or tsc will be more suitable for production builds.

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?

About

Super-fast alternative to Babel for when you can target modern JS runtimes

Topics

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published