CoolFace
Datasetpublic

basant307/AI_Governance_Project

sourceHugging Faceapache-2.0updated 2mo agoView on Hugging Face
0likes48downloads
README.md296 linesDownload Raw Back to sucrase
1# Sucrase2 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 usage12 13```bash14yarn add --dev sucrase  # Or npm install --save-dev sucrase15node -r sucrase/register main.ts16```17 18Using the [ts-node](https://github.com/TypeStrong/ts-node) integration:19 20```bash21yarn add --dev sucrase ts-node typescript22./node_modules/.bin/ts-node --transpiler sucrase/ts-node-plugin main.ts23```24 25## Project overview26 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 Internet29Explorer, Sucrase assumes that you're developing with a recent browser or recent30Node.js version, so it focuses on compiling non-standard language extensions:31JSX, TypeScript, and Flow. Because of this smaller scope, Sucrase can get away32with an architecture that is much more performant but less extensible and33maintainable. Sucrase's parser is forked from Babel's parser (so Sucrase is34indebted to Babel and wouldn't be possible without it) and trims it down to a35focused subset of what Babel solves. If it fits your use case, hopefully Sucrase36can speed up your development experience!37 38**Sucrase has been extensively tested.** It can successfully build39the [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), and44[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 how48Sucrase compares with other tools when compiling the Jest codebase 3 times,49about 360k lines of code total:50 51```text52            Time            Speed53Sucrase     0.57 seconds    636975 lines per second54swc         1.19 seconds    304526 lines per second55esbuild     1.45 seconds    248692 lines per second56TypeScript  8.98 seconds    40240 lines per second57Babel       9.18 seconds    39366 lines per second58```59 60Details: Measured on July 2022. Tools run in single-threaded mode without warm-up. See the61[benchmark code](https://github.com/alangpierce/sucrase/blob/main/benchmark/benchmark.ts)62for methodology and caveats.63 64## Transforms65 66The main configuration option in Sucrase is an array of transform names. These67transforms 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 type73  annotations and handling features like enums. Does not check types. Sucrase74  transforms each file independently, so you should enable the `isolatedModules`75  TypeScript flag so that the typechecker will disallow the few features like76  `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 TS78  `verbatimModuleSyntax`.79* **flow**:  Removes Flow type annotations. Does not check types.80* **imports**: Transforms ES Modules (`import`/`export`) to CommonJS81  (`require`/`module.exports`) using the same approach as Babel and TypeScript82  with `--esModuleInterop`. If `preserveDynamicImport` is specified in the Sucrase83  options, then dynamic `import` expressions are left alone, which is particularly84  useful in Node to load ESM-only libraries. If `preserveDynamicImport` is not85  specified, `import` expressions are transformed into a promise-wrapped call to86  `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 of90  bound methods.91* **jest**: Hoist desired [jest](https://jestjs.io/) method calls above imports in92  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), the96`injectCreateRequireForImportRequire` option can be specified to transform TS97`import foo = require("foo");` in a way that matches the98[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 specify113`disableESTransforms: true` so that Sucrase preserves the syntax rather than114trying to transform it. Note that transpiled and standard class fields behave115slightly differently; see the116[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 option118`useDefineForClassFields` to enable error checking related to these differences.119 120### Unsupported syntax121 122All JS syntax not mentioned above will "pass through" and needs to be supported123by 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 this127  writing), and Sucrase doesn't make an attempt to transpile them.128* Object rest/spread, async functions, and async iterators are all recent129  features that should work fine, but might cause issues if you use older130  versions of tools like webpack. BigInt and newer regex features may or may not131  work, based on your tooling.132 133### JSX Options134 135By default, JSX is compiled to React functions in development mode. This can be136configured 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 debugging149  information. When using React in production mode with the automatic transform, this *must* be150  set to true to avoid an error about `jsxDEV` being missing.151 152### Legacy CommonJS interop153 154Two legacy modes can be used with the `imports` transform:155 156* **enableLegacyTypeScriptModuleInterop**: Use the default TypeScript approach157  to CommonJS interop instead of assuming that TypeScript's `--esModuleInterop`158  flag is enabled. For example, if a CJS module exports a function, legacy159  TypeScript interop requires you to write `import * as add from './add';`,160  while Babel, Webpack, Node.js, and TypeScript with `--esModuleInterop` require161  you to write `import add from './add';`. As mentioned in the162  [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 CommonJS165  interop, so that you can run `require('./MyModule')` instead of166  `require('./MyModule').default`. Analogous to167  [babel-plugin-add-module-exports](https://github.com/59naga/babel-plugin-add-module-exports).168 169## Usage170 171### Tool integrations172 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 Node180 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```bash184ts-node --transpiler sucrase/ts-node-plugin185```186 187For projects that don't target ESM, Sucrase also has a require hook with some188reasonable 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` environment195variable holding a JSON string of options.196 197### Compiling a project to JS198 199For simple use cases, Sucrase comes with a `sucrase` CLI that mirrors your200directory structure to an output directory:201```bash202sucrase ./srcDir -d ./outDir --transforms typescript,imports203```204 205### Usage from code206 207For any advanced use cases, Sucrase can be called from JS directly:208 209```js210import {transform} from "sucrase";211const compiledCode = transform(code, {transforms: ["typescript", "imports"]}).code;212```213 214## What Sucrase is not215 216Sucrase is intended to be useful for the most common cases, but it does not aim217to 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 you220  give it valid code, it will produce valid JS code. If you give it invalid221  code, it might produce invalid code, it might produce valid code, or it might222  give an error. Always use Sucrase with a linter or typechecker, which is more223  suited for error-checking.224* Sucrase is not pluginizable. With the current architecture, transforms need to225  be explicitly written to cooperate with each other, so each additional226  transform takes significant extra work.227* Sucrase is not good for prototyping language extensions and upcoming language228  features. Its faster architecture makes new transforms more difficult to write229  and more fragile.230* Sucrase will never produce code for old browsers like IE. Compiling code down231  to ES5 is much more complicated than any transformation that Sucrase needs to232  do.233* Sucrase is hesitant to implement upcoming JS features, although some of them234  make sense to implement for pragmatic reasons. Its main focus is on language235  extensions (JSX, TypeScript, Flow) that will never be supported by JS236  runtimes.237* Like Babel, Sucrase is not a typechecker, and must process each file in238  isolation. For example, TypeScript `const enum`s are treated as regular239  `enum`s rather than inlining across files.240* You should think carefully before using Sucrase in production. Sucrase is241  mostly beneficial in development, and in many cases, Babel or tsc will be more242  suitable for production builds.243 244See the [Project Vision](./docs/PROJECT_VISION.md) document for more details on245the philosophy behind Sucrase.246 247## Motivation248 249As JavaScript implementations mature, it becomes more and more reasonable to250disable Babel transforms, especially in development when you know that you're251targeting a modern runtime. You might hope that you could simplify and speed up252the build step by eventually disabling Babel entirely, but this isn't possible253if 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 as255you 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 cost264to 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 fork269   of the Babel parser. This fork does not produce a full AST, but still270   produces meaningful token metadata specifically designed for the later271   transforms.2722. Scan through the tokens, computing preliminary information like all273   imported/exported names.2743. Run the transform by doing a pass through the tokens and performing a number275   of careful find-and-replace operations, like replacing `<Foo` with276   `React.createElement(Foo`.277 278Because Sucrase works on a lower level and uses a custom parser for its use279case, it is much faster than Babel.280 281## Contributing282 283Contributions are welcome, whether they be bug reports, PRs, docs, tests, or284anything else! Please take a look through the [Contributing Guide](./CONTRIBUTING.md)285to learn how to get started.286 287## License and attribution288 289Sucrase is MIT-licensed. A large part of Sucrase is based on a fork of the290[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?296 
basant307/AI_Governance_Project · CoolFace