yuku-codegen
A fast code generator for any ESTree / TypeScript-ESTree AST, with type stripping, minification, and Source Map V3 output, part of Yuku.
It is plain JavaScript with no native binary, and prints any ESTree AST, whichever parser produced it. Its output is byte-identical to Yuku's Zig printer, source maps included, and it runs 2.6x faster than @babel/generator, or 3x with source maps on.
Install
npm install yuku-codegen
Usage
import { generate } from "yuku-codegen";
import { parse } from "yuku-parser";
const { code } = generate(parse("const x = 1 + 2;").program);
Result
generate takes a Program node and returns a GenerateResult.
interface GenerateResult {
code: string;
diagnostics: Diagnostic[];
map: SourceMap | null;
}
diagnostics has the same shape as yuku-parser's.
Options
Every transformation is an independent flag, so they compose freely.
generate(program, { strip: true, minify: true, sourceMap: { source } });
strip | boolean | false | Drop TypeScript-only syntax. See Type stripping. |
minify | boolean | MinifyOptions | false | Minify the output. See Minification. |
format | "pretty" | "compact" | "pretty" | "compact" emits only the separators the grammar requires. |
indent | number | 2 | Spaces per level in pretty format, from 0 to 255. |
quotes | "preserve" | "double" | "single" | "shortest" | "preserve" | Quote style for string literals. See Quotes. |
comments | boolean | "all" | "some" | "none" | "line" | "block" | "some" | Which attached comments to emit. See Comments. |
sourceMap | SourceMapOptions | none | Emit a Source Map V3. See Source maps. |
Type stripping
strip: true prints a TypeScript AST as plain JavaScript.
generate(parse(`const x: number = 1;`, { lang: "ts" }).program, { strip: true }).code;
Types, interfaces, type aliases, generics, type assertions, satisfies, non-null !, declare, and abstract strip cleanly. A few TypeScript features emit runtime values: enum, namespace, module, export =, import = require(), and parameter properties. Converting them is transpilation, not stripping, so each one is reported in diagnostics and left out, a parameter property keeps its plain parameter, and the rest of the file is still emitted. Their ambient forms (declare enum, declare namespace, declare module, import type X = require(...)) carry no runtime and strip silently.
Minification
minify: true enables every switch. An object picks them, and enabled switches override format and quotes.
whitespace | Emit compact whitespace. |
syntax | Apply the size-reducing syntax rewrites below. |
quotes | Use whichever quote needs fewer escapes per literal. |
generate(program, { minify: { syntax: true } });
The syntax rewrites:
true and false become !0 and !1.
- Numeric literals take their shortest form (
1000000 becomes 1e6, 0.5 becomes .5).
obj["foo"] becomes obj.foo when the key is a valid identifier.
{ "foo": x } becomes { foo: x } when safe.
</script, <!--, and --> are escaped in strings and untagged template literals, so the output is safe to inline in a <script> tag. Tagged templates keep their raw text, since the tag reads it.
Quotes
"preserve" | Keep each literal's source quote style, re-escaping the content. |
"double" | Force double quotes. |
"single" | Force single quotes. |
"shortest" | Pick whichever quote needs fewer escapes per literal, double on a tie. |
Comments print from the nodes they are attached to, so parse with attachComments: true to keep them. Because they live on nodes, they move with their node through transforms.
"some" | Legal headers, JSDoc, and @/# annotations, the bundler convention. The default. |
"all" or true | Every comment. |
"none" or false | No comments. |
"line" | // ... only. |
"block" | /* ... */ only. |
const { program } = parse(`// hello\nconst x = 1;`, { attachComments: true });
generate(program, { comments: true }).code;
Source maps
Pass the original source to emit a Source Map V3 alongside the code.
const { code, map } = generate(program, {
sourceMap: { source, file: "out.js", sourceFileName: "in.js", sourcesContent: source },
});
const output = `${code}\n//# sourceMappingURL=out.js.map`;
const mapJson = JSON.stringify(map);
source | Required. The original source text, positions map to it. |
file | Output filename, embedded as file. |
sourceFileName | Source filename, the single entry of sources. |
sourceRoot | Embedded as sourceRoot. |
sourcesContent | The single entry of sourcesContent. |
map is a Source Map V3 object, ready for JSON.stringify. Columns are 0-indexed UTF-16 code units, the convention of browser devtools and source map libraries.
interface SourceMap {
version: 3;
file: string | null;
sourceRoot: string | null;
sources: string[];
sourcesContent: (string | null)[] | null;
names: string[];
mappings: string;
}
License
MIT