| [9af201e] | 1 | # Sucrase
|
|---|
| 2 |
|
|---|
| 3 | [](https://github.com/alangpierce/sucrase/actions)
|
|---|
| 4 | [](https://www.npmjs.com/package/sucrase)
|
|---|
| 5 | [](https://packagephobia.now.sh/result?p=sucrase)
|
|---|
| 6 | [](LICENSE)
|
|---|
| 7 | [](https://gitter.im/sucrasejs/Lobby)
|
|---|
| 8 |
|
|---|
| 9 | ## [Try it out](https://sucrase.io)
|
|---|
| 10 |
|
|---|
| 11 | ## Quick usage
|
|---|
| 12 |
|
|---|
| 13 | ```bash
|
|---|
| 14 | yarn add --dev sucrase # Or npm install --save-dev sucrase
|
|---|
| 15 | node -r sucrase/register main.ts
|
|---|
| 16 | ```
|
|---|
| 17 |
|
|---|
| 18 | Using the [ts-node](https://github.com/TypeStrong/ts-node) integration:
|
|---|
| 19 |
|
|---|
| 20 | ```bash
|
|---|
| 21 | yarn add --dev sucrase ts-node typescript
|
|---|
| 22 | ./node_modules/.bin/ts-node --transpiler sucrase/ts-node-plugin main.ts
|
|---|
| 23 | ```
|
|---|
| 24 |
|
|---|
| 25 | ## Project overview
|
|---|
| 26 |
|
|---|
| 27 | Sucrase is an alternative to Babel that allows super-fast development builds.
|
|---|
| 28 | Instead of compiling a large range of JS features to be able to work in Internet
|
|---|
| 29 | Explorer, Sucrase assumes that you're developing with a recent browser or recent
|
|---|
| 30 | Node.js version, so it focuses on compiling non-standard language extensions:
|
|---|
| 31 | JSX, TypeScript, and Flow. Because of this smaller scope, Sucrase can get away
|
|---|
| 32 | with an architecture that is much more performant but less extensible and
|
|---|
| 33 | maintainable. Sucrase's parser is forked from Babel's parser (so Sucrase is
|
|---|
| 34 | indebted to Babel and wouldn't be possible without it) and trims it down to a
|
|---|
| 35 | focused subset of what Babel solves. If it fits your use case, hopefully Sucrase
|
|---|
| 36 | can speed up your development experience!
|
|---|
| 37 |
|
|---|
| 38 | **Sucrase has been extensively tested.** It can successfully build
|
|---|
| 39 | the [Benchling](https://benchling.com/) frontend code,
|
|---|
| 40 | [Babel](https://github.com/babel/babel),
|
|---|
| 41 | [React](https://github.com/facebook/react),
|
|---|
| 42 | [TSLint](https://github.com/palantir/tslint),
|
|---|
| 43 | [Apollo client](https://github.com/apollographql/apollo-client), and
|
|---|
| 44 | [decaffeinate](https://github.com/decaffeinate/decaffeinate)
|
|---|
| 45 | with all tests passing, about 1 million lines of code total.
|
|---|
| 46 |
|
|---|
| 47 | **Sucrase is about 20x faster than Babel.** Here's one measurement of how
|
|---|
| 48 | Sucrase compares with other tools when compiling the Jest codebase 3 times,
|
|---|
| 49 | about 360k lines of code total:
|
|---|
| 50 |
|
|---|
| 51 | ```text
|
|---|
| 52 | Time Speed
|
|---|
| 53 | Sucrase 0.57 seconds 636975 lines per second
|
|---|
| 54 | swc 1.19 seconds 304526 lines per second
|
|---|
| 55 | esbuild 1.45 seconds 248692 lines per second
|
|---|
| 56 | TypeScript 8.98 seconds 40240 lines per second
|
|---|
| 57 | Babel 9.18 seconds 39366 lines per second
|
|---|
| 58 | ```
|
|---|
| 59 |
|
|---|
| 60 | Details: Measured on July 2022. Tools run in single-threaded mode without warm-up. See the
|
|---|
| 61 | [benchmark code](https://github.com/alangpierce/sucrase/blob/main/benchmark/benchmark.ts)
|
|---|
| 62 | for methodology and caveats.
|
|---|
| 63 |
|
|---|
| 64 | ## Transforms
|
|---|
| 65 |
|
|---|
| 66 | The main configuration option in Sucrase is an array of transform names. These
|
|---|
| 67 | transforms are available:
|
|---|
| 68 |
|
|---|
| 69 | * **jsx**: Enables JSX syntax. By default, JSX is transformed to `React.createClass`,
|
|---|
| 70 | but may be preserved or transformed to `_jsx()` by setting the `jsxRuntime` option.
|
|---|
| 71 | Also adds `createReactClass` display names and JSX context information.
|
|---|
| 72 | * **typescript**: Compiles TypeScript code to JavaScript, removing type
|
|---|
| 73 | annotations and handling features like enums. Does not check types. Sucrase
|
|---|
| 74 | transforms each file independently, so you should enable the `isolatedModules`
|
|---|
| 75 | TypeScript flag so that the typechecker will disallow the few features like
|
|---|
| 76 | `const enum`s that need cross-file compilation. The Sucrase option `keepUnusedImports`
|
|---|
| 77 | can be used to disable all automatic removal of imports and exports, analogous to TS
|
|---|
| 78 | `verbatimModuleSyntax`.
|
|---|
| 79 | * **flow**: Removes Flow type annotations. Does not check types.
|
|---|
| 80 | * **imports**: Transforms ES Modules (`import`/`export`) to CommonJS
|
|---|
| 81 | (`require`/`module.exports`) using the same approach as Babel and TypeScript
|
|---|
| 82 | with `--esModuleInterop`. If `preserveDynamicImport` is specified in the Sucrase
|
|---|
| 83 | options, then dynamic `import` expressions are left alone, which is particularly
|
|---|
| 84 | useful in Node to load ESM-only libraries. If `preserveDynamicImport` is not
|
|---|
| 85 | specified, `import` expressions are transformed into a promise-wrapped call to
|
|---|
| 86 | `require`.
|
|---|
| 87 | * **react-hot-loader**: Performs the equivalent of the `react-hot-loader/babel`
|
|---|
| 88 | transform in the [react-hot-loader](https://github.com/gaearon/react-hot-loader)
|
|---|
| 89 | project. This enables advanced hot reloading use cases such as editing of
|
|---|
| 90 | bound methods.
|
|---|
| 91 | * **jest**: Hoist desired [jest](https://jestjs.io/) method calls above imports in
|
|---|
| 92 | the same way as [babel-plugin-jest-hoist](https://github.com/facebook/jest/tree/master/packages/babel-plugin-jest-hoist).
|
|---|
| 93 | Does not validate the arguments passed to `jest.mock`, but the same rules still apply.
|
|---|
| 94 |
|
|---|
| 95 | When the `imports` transform is *not* specified (i.e. when targeting ESM), the
|
|---|
| 96 | `injectCreateRequireForImportRequire` option can be specified to transform TS
|
|---|
| 97 | `import foo = require("foo");` in a way that matches the
|
|---|
| 98 | [TypeScript 4.7 behavior](https://devblogs.microsoft.com/typescript/announcing-typescript-4-7/#commonjs-interoperability)
|
|---|
| 99 | with `module: nodenext`.
|
|---|
| 100 |
|
|---|
| 101 | These newer JS features are transformed by default:
|
|---|
| 102 |
|
|---|
| 103 | * [Optional chaining](https://github.com/tc39/proposal-optional-chaining): `a?.b`
|
|---|
| 104 | * [Nullish coalescing](https://github.com/tc39/proposal-nullish-coalescing): `a ?? b`
|
|---|
| 105 | * [Class fields](https://github.com/tc39/proposal-class-fields): `class C { x = 1; }`.
|
|---|
| 106 | This includes static fields but not the `#x` private field syntax.
|
|---|
| 107 | * [Numeric separators](https://github.com/tc39/proposal-numeric-separator):
|
|---|
| 108 | `const n = 1_234;`
|
|---|
| 109 | * [Optional catch binding](https://github.com/tc39/proposal-optional-catch-binding):
|
|---|
| 110 | `try { doThing(); } catch { }`.
|
|---|
| 111 |
|
|---|
| 112 | If your target runtime supports these features, you can specify
|
|---|
| 113 | `disableESTransforms: true` so that Sucrase preserves the syntax rather than
|
|---|
| 114 | trying to transform it. Note that transpiled and standard class fields behave
|
|---|
| 115 | slightly differently; see the
|
|---|
| 116 | [TypeScript 3.7 release notes](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#the-usedefineforclassfields-flag-and-the-declare-property-modifier)
|
|---|
| 117 | for details. If you use TypeScript, you can enable the TypeScript option
|
|---|
| 118 | `useDefineForClassFields` to enable error checking related to these differences.
|
|---|
| 119 |
|
|---|
| 120 | ### Unsupported syntax
|
|---|
| 121 |
|
|---|
| 122 | All JS syntax not mentioned above will "pass through" and needs to be supported
|
|---|
| 123 | by your JS runtime. For example:
|
|---|
| 124 |
|
|---|
| 125 | * Decorators, private fields, `throw` expressions, generator arrow functions,
|
|---|
| 126 | and `do` expressions are all unsupported in browsers and Node (as of this
|
|---|
| 127 | writing), and Sucrase doesn't make an attempt to transpile them.
|
|---|
| 128 | * Object rest/spread, async functions, and async iterators are all recent
|
|---|
| 129 | features that should work fine, but might cause issues if you use older
|
|---|
| 130 | versions of tools like webpack. BigInt and newer regex features may or may not
|
|---|
| 131 | work, based on your tooling.
|
|---|
| 132 |
|
|---|
| 133 | ### JSX Options
|
|---|
| 134 |
|
|---|
| 135 | By default, JSX is compiled to React functions in development mode. This can be
|
|---|
| 136 | configured with a few options:
|
|---|
| 137 |
|
|---|
| 138 | * **jsxRuntime**: A string specifying the transform mode, which can be one of three values:
|
|---|
| 139 | * `"classic"` (default): The original JSX transform that calls `React.createElement` by default.
|
|---|
| 140 | To configure for non-React use cases, specify:
|
|---|
| 141 | * **jsxPragma**: Element creation function, defaults to `React.createElement`.
|
|---|
| 142 | * **jsxFragmentPragma**: Fragment component, defaults to `React.Fragment`.
|
|---|
| 143 | * `"automatic"`: The [new JSX transform](https://reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html)
|
|---|
| 144 | introduced with React 17, which calls `jsx` functions and auto-adds import statements.
|
|---|
| 145 | To configure for non-React use cases, specify:
|
|---|
| 146 | * **jsxImportSource**: Package name for auto-generated import statements, defaults to `react`.
|
|---|
| 147 | * `"preserve"`: Don't transform JSX, and instead emit it as-is in the output code.
|
|---|
| 148 | * **production**: If `true`, use production version of functions and don't include debugging
|
|---|
| 149 | information. When using React in production mode with the automatic transform, this *must* be
|
|---|
| 150 | set to true to avoid an error about `jsxDEV` being missing.
|
|---|
| 151 |
|
|---|
| 152 | ### Legacy CommonJS interop
|
|---|
| 153 |
|
|---|
| 154 | Two legacy modes can be used with the `imports` transform:
|
|---|
| 155 |
|
|---|
| 156 | * **enableLegacyTypeScriptModuleInterop**: Use the default TypeScript approach
|
|---|
| 157 | to CommonJS interop instead of assuming that TypeScript's `--esModuleInterop`
|
|---|
| 158 | flag is enabled. For example, if a CJS module exports a function, legacy
|
|---|
| 159 | TypeScript interop requires you to write `import * as add from './add';`,
|
|---|
| 160 | while Babel, Webpack, Node.js, and TypeScript with `--esModuleInterop` require
|
|---|
| 161 | you to write `import add from './add';`. As mentioned in the
|
|---|
| 162 | [docs](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#support-for-import-d-from-cjs-form-commonjs-modules-with---esmoduleinterop),
|
|---|
| 163 | the TypeScript team recommends you always use `--esModuleInterop`.
|
|---|
| 164 | * **enableLegacyBabel5ModuleInterop**: Use the Babel 5 approach to CommonJS
|
|---|
| 165 | interop, so that you can run `require('./MyModule')` instead of
|
|---|
| 166 | `require('./MyModule').default`. Analogous to
|
|---|
| 167 | [babel-plugin-add-module-exports](https://github.com/59naga/babel-plugin-add-module-exports).
|
|---|
| 168 |
|
|---|
| 169 | ## Usage
|
|---|
| 170 |
|
|---|
| 171 | ### Tool integrations
|
|---|
| 172 |
|
|---|
| 173 | * [Webpack](https://github.com/alangpierce/sucrase/tree/main/integrations/webpack-loader)
|
|---|
| 174 | * [Gulp](https://github.com/alangpierce/sucrase/tree/main/integrations/gulp-plugin)
|
|---|
| 175 | * [Jest](https://github.com/alangpierce/sucrase/tree/main/integrations/jest-plugin)
|
|---|
| 176 | * [Rollup](https://github.com/rollup/plugins/tree/master/packages/sucrase)
|
|---|
| 177 | * [Broccoli](https://github.com/stefanpenner/broccoli-sucrase)
|
|---|
| 178 |
|
|---|
| 179 | ### Usage in Node
|
|---|
| 180 |
|
|---|
| 181 | The most robust way is to use the Sucrase plugin for [ts-node](https://github.com/TypeStrong/ts-node),
|
|---|
| 182 | which has various Node integrations and configures Sucrase via `tsconfig.json`:
|
|---|
| 183 | ```bash
|
|---|
| 184 | ts-node --transpiler sucrase/ts-node-plugin
|
|---|
| 185 | ```
|
|---|
| 186 |
|
|---|
| 187 | For projects that don't target ESM, Sucrase also has a require hook with some
|
|---|
| 188 | reasonable defaults that can be accessed in a few ways:
|
|---|
| 189 |
|
|---|
| 190 | * From code: `require("sucrase/register");`
|
|---|
| 191 | * When invoking Node: `node -r sucrase/register main.ts`
|
|---|
| 192 | * As a separate binary: `sucrase-node main.ts`
|
|---|
| 193 |
|
|---|
| 194 | Options can be passed to the require hook via a `SUCRASE_OPTIONS` environment
|
|---|
| 195 | variable holding a JSON string of options.
|
|---|
| 196 |
|
|---|
| 197 | ### Compiling a project to JS
|
|---|
| 198 |
|
|---|
| 199 | For simple use cases, Sucrase comes with a `sucrase` CLI that mirrors your
|
|---|
| 200 | directory structure to an output directory:
|
|---|
| 201 | ```bash
|
|---|
| 202 | sucrase ./srcDir -d ./outDir --transforms typescript,imports
|
|---|
| 203 | ```
|
|---|
| 204 |
|
|---|
| 205 | ### Usage from code
|
|---|
| 206 |
|
|---|
| 207 | For any advanced use cases, Sucrase can be called from JS directly:
|
|---|
| 208 |
|
|---|
| 209 | ```js
|
|---|
| 210 | import {transform} from "sucrase";
|
|---|
| 211 | const compiledCode = transform(code, {transforms: ["typescript", "imports"]}).code;
|
|---|
| 212 | ```
|
|---|
| 213 |
|
|---|
| 214 | ## What Sucrase is not
|
|---|
| 215 |
|
|---|
| 216 | Sucrase is intended to be useful for the most common cases, but it does not aim
|
|---|
| 217 | to have nearly the scope and versatility of Babel. Some specific examples:
|
|---|
| 218 |
|
|---|
| 219 | * Sucrase does not check your code for errors. Sucrase's contract is that if you
|
|---|
| 220 | give it valid code, it will produce valid JS code. If you give it invalid
|
|---|
| 221 | code, it might produce invalid code, it might produce valid code, or it might
|
|---|
| 222 | give an error. Always use Sucrase with a linter or typechecker, which is more
|
|---|
| 223 | suited for error-checking.
|
|---|
| 224 | * Sucrase is not pluginizable. With the current architecture, transforms need to
|
|---|
| 225 | be explicitly written to cooperate with each other, so each additional
|
|---|
| 226 | transform takes significant extra work.
|
|---|
| 227 | * Sucrase is not good for prototyping language extensions and upcoming language
|
|---|
| 228 | features. Its faster architecture makes new transforms more difficult to write
|
|---|
| 229 | and more fragile.
|
|---|
| 230 | * Sucrase will never produce code for old browsers like IE. Compiling code down
|
|---|
| 231 | to ES5 is much more complicated than any transformation that Sucrase needs to
|
|---|
| 232 | do.
|
|---|
| 233 | * Sucrase is hesitant to implement upcoming JS features, although some of them
|
|---|
| 234 | make sense to implement for pragmatic reasons. Its main focus is on language
|
|---|
| 235 | extensions (JSX, TypeScript, Flow) that will never be supported by JS
|
|---|
| 236 | runtimes.
|
|---|
| 237 | * Like Babel, Sucrase is not a typechecker, and must process each file in
|
|---|
| 238 | isolation. For example, TypeScript `const enum`s are treated as regular
|
|---|
| 239 | `enum`s rather than inlining across files.
|
|---|
| 240 | * You should think carefully before using Sucrase in production. Sucrase is
|
|---|
| 241 | mostly beneficial in development, and in many cases, Babel or tsc will be more
|
|---|
| 242 | suitable for production builds.
|
|---|
| 243 |
|
|---|
| 244 | See the [Project Vision](./docs/PROJECT_VISION.md) document for more details on
|
|---|
| 245 | the philosophy behind Sucrase.
|
|---|
| 246 |
|
|---|
| 247 | ## Motivation
|
|---|
| 248 |
|
|---|
| 249 | As JavaScript implementations mature, it becomes more and more reasonable to
|
|---|
| 250 | disable Babel transforms, especially in development when you know that you're
|
|---|
| 251 | targeting a modern runtime. You might hope that you could simplify and speed up
|
|---|
| 252 | the build step by eventually disabling Babel entirely, but this isn't possible
|
|---|
| 253 | if you're using a non-standard language extension like JSX, TypeScript, or Flow.
|
|---|
| 254 | Unfortunately, disabling most transforms in Babel doesn't speed it up as much as
|
|---|
| 255 | you might expect. To understand, let's take a look at how Babel works:
|
|---|
| 256 |
|
|---|
| 257 | 1. Tokenize the input source code into a token stream.
|
|---|
| 258 | 2. Parse the token stream into an AST.
|
|---|
| 259 | 3. Walk the AST to compute the scope information for each variable.
|
|---|
| 260 | 4. Apply all transform plugins in a single traversal, resulting in a new AST.
|
|---|
| 261 | 5. Print the resulting AST.
|
|---|
| 262 |
|
|---|
| 263 | Only step 4 gets faster when disabling plugins, so there's always a fixed cost
|
|---|
| 264 | to running Babel regardless of how many transforms are enabled.
|
|---|
| 265 |
|
|---|
| 266 | Sucrase bypasses most of these steps, and works like this:
|
|---|
| 267 |
|
|---|
| 268 | 1. Tokenize the input source code into a token stream using a trimmed-down fork
|
|---|
| 269 | of the Babel parser. This fork does not produce a full AST, but still
|
|---|
| 270 | produces meaningful token metadata specifically designed for the later
|
|---|
| 271 | transforms.
|
|---|
| 272 | 2. Scan through the tokens, computing preliminary information like all
|
|---|
| 273 | imported/exported names.
|
|---|
| 274 | 3. Run the transform by doing a pass through the tokens and performing a number
|
|---|
| 275 | of careful find-and-replace operations, like replacing `<Foo` with
|
|---|
| 276 | `React.createElement(Foo`.
|
|---|
| 277 |
|
|---|
| 278 | Because Sucrase works on a lower level and uses a custom parser for its use
|
|---|
| 279 | case, it is much faster than Babel.
|
|---|
| 280 |
|
|---|
| 281 | ## Contributing
|
|---|
| 282 |
|
|---|
| 283 | Contributions are welcome, whether they be bug reports, PRs, docs, tests, or
|
|---|
| 284 | anything else! Please take a look through the [Contributing Guide](./CONTRIBUTING.md)
|
|---|
| 285 | to learn how to get started.
|
|---|
| 286 |
|
|---|
| 287 | ## License and attribution
|
|---|
| 288 |
|
|---|
| 289 | Sucrase is MIT-licensed. A large part of Sucrase is based on a fork of the
|
|---|
| 290 | [Babel parser](https://github.com/babel/babel/tree/main/packages/babel-parser),
|
|---|
| 291 | which is also MIT-licensed.
|
|---|
| 292 |
|
|---|
| 293 | ## Why the name?
|
|---|
| 294 |
|
|---|
| 295 | Sucrase is an enzyme that processes sugar. Get it?
|
|---|