UNPKG

12.4 kBMarkdownView Raw
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
11Sucrase is an alternative to Babel that allows super-fast development builds.
12Instead of compiling a large range of JS features to be able to work in Internet
13Explorer, Sucrase assumes that you're developing with a recent browser or recent
14Node.js version, so it focuses on compiling non-standard language extensions:
15JSX, TypeScript, and Flow. Because of this smaller scope, Sucrase can get away
16with an architecture that is much more performant but less extensible and
17maintainable. Sucrase's parser is forked from Babel's parser (so Sucrase is
18indebted to Babel and wouldn't be possible without it) and trims it down to a
19focused subset of what Babel solves. If it fits your use case, hopefully Sucrase
20can speed up your development experience!
21
22**Sucrase has been extensively tested.** It can successfully build
23the [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)
29with 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
32Sucrase compares with other tools when compiling the Jest codebase 3 times,
33about 360k lines of code total:
34
35```text
36 Time Speed
37Sucrase 1.64 seconds 220221 lines per second
38swc 2.13 seconds 169502 lines per second
39esbuild 3.02 seconds 119738 lines per second
40TypeScript 24.18 seconds 14937 lines per second
41Babel 27.22 seconds 13270 lines per second
42```
43
44Details: 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)
46for methodology and caveats.
47
48## Transforms
49
50The main configuration option in Sucrase is an array of transform names. These
51transforms 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
74These 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
85If your target runtime supports these features, you can specify
86`disableESTransforms: true` so that Sucrase preserves the syntax rather than
87trying to transform it. Note that transpiled and standard class fields behave
88slightly 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)
90for 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
95All JS syntax not mentioned above will "pass through" and needs to be supported
96by 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
108Like Babel, Sucrase compiles JSX to React functions by default, but can be
109configured 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
116Two 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
133Installation:
134
135```bash
136yarn add --dev sucrase # Or npm install --save-dev sucrase
137```
138
139Often, 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
146Compile on-the-fly via a require hook with some [reasonable defaults](src/register.ts):
147
148```js
149// Register just one extension.
150require("sucrase/register/ts");
151// Or register all at once.
152require("sucrase/register");
153```
154
155Compile on-the-fly via a drop-in replacement for node:
156
157```bash
158sucrase-node index.ts
159```
160
161Run on a directory:
162
163```bash
164sucrase ./srcDir -d ./outDir --transforms typescript,imports
165```
166
167Call from JS directly:
168
169```js
170import {transform} from "sucrase";
171const compiledCode = transform(code, {transforms: ["typescript", "imports"]}).code;
172```
173
174## What Sucrase is not
175
176Sucrase is intended to be useful for the most common cases, but it does not aim
177to 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
204See the [Project Vision](./docs/PROJECT_VISION.md) document for more details on
205the philosophy behind Sucrase.
206
207## Motivation
208
209As JavaScript implementations mature, it becomes more and more reasonable to
210disable Babel transforms, especially in development when you know that you're
211targeting a modern runtime. You might hope that you could simplify and speed up
212the build step by eventually disabling Babel entirely, but this isn't possible
213if you're using a non-standard language extension like JSX, TypeScript, or Flow.
214Unfortunately, disabling most transforms in Babel doesn't speed it up as much as
215you might expect. To understand, let's take a look at how Babel works:
216
2171. Tokenize the input source code into a token stream.
2182. Parse the token stream into an AST.
2193. Walk the AST to compute the scope information for each variable.
2204. Apply all transform plugins in a single traversal, resulting in a new AST.
2215. Print the resulting AST.
222
223Only step 4 gets faster when disabling plugins, so there's always a fixed cost
224to running Babel regardless of how many transforms are enabled.
225
226Sucrase bypasses most of these steps, and works like this:
227
2281. 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.
2322. Scan through the tokens, computing preliminary information like all
233 imported/exported names.
2343. 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
238Because Sucrase works on a lower level and uses a custom parser for its use
239case, it is much faster than Babel.
240
241## Contributing
242
243Contributions are welcome, whether they be bug reports, PRs, docs, tests, or
244anything else! Please take a look through the [Contributing Guide](./CONTRIBUTING.md)
245to learn how to get started.
246
247## License and attribution
248
249Sucrase 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),
251which is also MIT-licensed.
252
253## Why the name?
254
255Sucrase is an enzyme that processes sugar. Get it?