UNPKG

14.8 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
11## Quick usage
12
13```bash
14yarn add --dev sucrase # Or npm install --save-dev sucrase
15node -r sucrase/register main.ts
16```
17
18Using the [ts-node](https://github.com/TypeStrong/ts-node) integration:
19
20```bash
21yarn 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
27Sucrase is an alternative to Babel that allows super-fast development builds.
28Instead of compiling a large range of JS features to be able to work in Internet
29Explorer, Sucrase assumes that you're developing with a recent browser or recent
30Node.js version, so it focuses on compiling non-standard language extensions:
31JSX, TypeScript, and Flow. Because of this smaller scope, Sucrase can get away
32with an architecture that is much more performant but less extensible and
33maintainable. Sucrase's parser is forked from Babel's parser (so Sucrase is
34indebted to Babel and wouldn't be possible without it) and trims it down to a
35focused subset of what Babel solves. If it fits your use case, hopefully Sucrase
36can speed up your development experience!
37
38**Sucrase has been extensively tested.** It can successfully build
39the [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)
45with 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
48Sucrase compares with other tools when compiling the Jest codebase 3 times,
49about 360k lines of code total:
50
51```text
52 Time Speed
53Sucrase 0.57 seconds 636975 lines per second
54swc 1.19 seconds 304526 lines per second
55esbuild 1.45 seconds 248692 lines per second
56TypeScript 8.98 seconds 40240 lines per second
57Babel 9.18 seconds 39366 lines per second
58```
59
60Details: 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)
62for methodology and caveats.
63
64## Transforms
65
66The main configuration option in Sucrase is an array of transform names. These
67transforms 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
95When 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)
99with `module: nodenext`.
100
101These 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
112If your target runtime supports these features, you can specify
113`disableESTransforms: true` so that Sucrase preserves the syntax rather than
114trying to transform it. Note that transpiled and standard class fields behave
115slightly 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)
117for 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
122All JS syntax not mentioned above will "pass through" and needs to be supported
123by 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
135By default, JSX is compiled to React functions in development mode. This can be
136configured 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
154Two 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
181The most robust way is to use the Sucrase plugin for [ts-node](https://github.com/TypeStrong/ts-node),
182which has various Node integrations and configures Sucrase via `tsconfig.json`:
183```bash
184ts-node --transpiler sucrase/ts-node-plugin
185```
186
187For projects that don't target ESM, Sucrase also has a require hook with some
188reasonable 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
194Options can be passed to the require hook via a `SUCRASE_OPTIONS` environment
195variable holding a JSON string of options.
196
197### Compiling a project to JS
198
199For simple use cases, Sucrase comes with a `sucrase` CLI that mirrors your
200directory structure to an output directory:
201```bash
202sucrase ./srcDir -d ./outDir --transforms typescript,imports
203```
204
205### Usage from code
206
207For any advanced use cases, Sucrase can be called from JS directly:
208
209```js
210import {transform} from "sucrase";
211const compiledCode = transform(code, {transforms: ["typescript", "imports"]}).code;
212```
213
214## What Sucrase is not
215
216Sucrase is intended to be useful for the most common cases, but it does not aim
217to 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
244See the [Project Vision](./docs/PROJECT_VISION.md) document for more details on
245the philosophy behind Sucrase.
246
247## Motivation
248
249As JavaScript implementations mature, it becomes more and more reasonable to
250disable Babel transforms, especially in development when you know that you're
251targeting a modern runtime. You might hope that you could simplify and speed up
252the build step by eventually disabling Babel entirely, but this isn't possible
253if you're using a non-standard language extension like JSX, TypeScript, or Flow.
254Unfortunately, disabling most transforms in Babel doesn't speed it up as much as
255you might expect. To understand, let's take a look at how Babel works:
256
2571. Tokenize the input source code into a token stream.
2582. Parse the token stream into an AST.
2593. Walk the AST to compute the scope information for each variable.
2604. Apply all transform plugins in a single traversal, resulting in a new AST.
2615. Print the resulting AST.
262
263Only step 4 gets faster when disabling plugins, so there's always a fixed cost
264to running Babel regardless of how many transforms are enabled.
265
266Sucrase bypasses most of these steps, and works like this:
267
2681. 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.
2722. Scan through the tokens, computing preliminary information like all
273 imported/exported names.
2743. 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
278Because Sucrase works on a lower level and uses a custom parser for its use
279case, it is much faster than Babel.
280
281## Contributing
282
283Contributions are welcome, whether they be bug reports, PRs, docs, tests, or
284anything else! Please take a look through the [Contributing Guide](./CONTRIBUTING.md)
285to learn how to get started.
286
287## License and attribution
288
289Sucrase 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),
291which is also MIT-licensed.
292
293## Why the name?
294
295Sucrase is an enzyme that processes sugar. Get it?