UNPKG

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