UNPKG

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