UNPKG

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