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