UNPKG

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