-
Notifications
You must be signed in to change notification settings - Fork 138
/
cli.ts
317 lines (280 loc) · 9.69 KB
/
cli.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
/* eslint-disable no-console */
import commander from "commander";
import {glob} from "glob";
import {exists, mkdir, readdir, readFile, stat, writeFile} from "mz/fs";
import {dirname, join, relative} from "path";
import {type Options, transform} from "./index";
interface CLIOptions {
outDirPath: string;
srcDirPath: string;
project: string;
outExtension: string;
excludeDirs: Array<string>;
quiet: boolean;
sucraseOptions: Options;
}
export default function run(): void {
commander
.description(`Sucrase: super-fast Babel alternative.`)
.usage("[options] <srcDir>")
.option(
"-d, --out-dir <out>",
"Compile an input directory of modules into an output directory.",
)
.option(
"-p, --project <dir>",
"Compile a TypeScript project, will read from tsconfig.json in <dir>",
)
.option("--out-extension <extension>", "File extension to use for all output files.", "js")
.option("--exclude-dirs <paths>", "Names of directories that should not be traversed.")
.option("-q, --quiet", "Don't print the names of converted files.")
.option("-t, --transforms <transforms>", "Comma-separated list of transforms to run.")
.option("--disable-es-transforms", "Opt out of all ES syntax transforms.")
.option("--jsx-runtime <string>", "Transformation mode for the JSX transform.")
.option("--production", "Disable debugging information from JSX in output.")
.option(
"--jsx-import-source <string>",
"Automatic JSX transform import path prefix, defaults to `React.Fragment`.",
)
.option(
"--jsx-pragma <string>",
"Classic JSX transform element creation function, defaults to `React.createElement`.",
)
.option(
"--jsx-fragment-pragma <string>",
"Classic JSX transform fragment component, defaults to `React.Fragment`.",
)
.option("--keep-unused-imports", "Disable automatic removal of type-only imports/exports.")
.option("--preserve-dynamic-import", "Don't transpile dynamic import() to require.")
.option(
"--inject-create-require-for-import-require",
"Use `createRequire` when transpiling TS `import = require` to ESM.",
)
.option(
"--enable-legacy-typescript-module-interop",
"Use default TypeScript ESM/CJS interop strategy.",
)
.option("--enable-legacy-babel5-module-interop", "Use Babel 5 ESM/CJS interop strategy.")
.parse(process.argv);
if (commander.project) {
if (
commander.outDir ||
commander.transforms ||
commander.args[0] ||
commander.enableLegacyTypescriptModuleInterop
) {
console.error(
"If TypeScript project is specified, out directory, transforms, source " +
"directory, and --enable-legacy-typescript-module-interop may not be specified.",
);
process.exit(1);
}
} else {
if (!commander.outDir) {
console.error("Out directory is required");
process.exit(1);
}
if (!commander.transforms) {
console.error("Transforms option is required.");
process.exit(1);
}
if (!commander.args[0]) {
console.error("Source directory is required.");
process.exit(1);
}
}
const options: CLIOptions = {
outDirPath: commander.outDir,
srcDirPath: commander.args[0],
project: commander.project,
outExtension: commander.outExtension,
excludeDirs: commander.excludeDirs ? commander.excludeDirs.split(",") : [],
quiet: commander.quiet,
sucraseOptions: {
transforms: commander.transforms ? commander.transforms.split(",") : [],
disableESTransforms: commander.disableEsTransforms,
jsxRuntime: commander.jsxRuntime,
production: commander.production,
jsxImportSource: commander.jsxImportSource,
jsxPragma: commander.jsxPragma || "React.createElement",
jsxFragmentPragma: commander.jsxFragmentPragma || "React.Fragment",
keepUnusedImports: commander.keepUnusedImports,
preserveDynamicImport: commander.preserveDynamicImport,
injectCreateRequireForImportRequire: commander.injectCreateRequireForImportRequire,
enableLegacyTypeScriptModuleInterop: commander.enableLegacyTypescriptModuleInterop,
enableLegacyBabel5ModuleInterop: commander.enableLegacyBabel5ModuleInterop,
},
};
buildDirectory(options).catch((e) => {
process.exitCode = 1;
console.error(e);
});
}
interface FileInfo {
srcPath: string;
outPath: string;
}
async function findFiles(options: CLIOptions): Promise<Array<FileInfo>> {
const outDirPath = options.outDirPath;
const srcDirPath = options.srcDirPath;
const extensions = options.sucraseOptions.transforms.includes("typescript")
? [".ts", ".tsx"]
: [".js", ".jsx"];
if (!(await exists(outDirPath))) {
await mkdir(outDirPath);
}
const outArr: Array<FileInfo> = [];
for (const child of await readdir(srcDirPath)) {
if (["node_modules", ".git"].includes(child) || options.excludeDirs.includes(child)) {
continue;
}
const srcChildPath = join(srcDirPath, child);
const outChildPath = join(outDirPath, child);
if ((await stat(srcChildPath)).isDirectory()) {
const innerOptions = {...options};
innerOptions.srcDirPath = srcChildPath;
innerOptions.outDirPath = outChildPath;
const innerFiles = await findFiles(innerOptions);
outArr.push(...innerFiles);
} else if (extensions.some((ext) => srcChildPath.endsWith(ext))) {
const outPath = outChildPath.replace(/\.\w+$/, `.${options.outExtension}`);
outArr.push({
srcPath: srcChildPath,
outPath,
});
}
}
return outArr;
}
async function runGlob(options: CLIOptions): Promise<Array<FileInfo>> {
const tsConfigPath = join(options.project, "tsconfig.json");
let str;
try {
str = await readFile(tsConfigPath, "utf8");
} catch (err) {
console.error("Could not find project tsconfig.json");
console.error(` --project=${options.project}`);
console.error(err);
process.exit(1);
}
const json = JSON.parse(str);
const foundFiles: Array<FileInfo> = [];
const files = json.files;
const include = json.include;
const absProject = join(process.cwd(), options.project);
const outDirs: Array<string> = [];
if (!(await exists(options.outDirPath))) {
await mkdir(options.outDirPath);
}
if (files) {
for (const file of files) {
if (file.endsWith(".d.ts")) {
continue;
}
if (!file.endsWith(".ts") && !file.endsWith(".js")) {
continue;
}
const srcFile = join(absProject, file);
const outFile = join(options.outDirPath, file);
const outPath = outFile.replace(/\.\w+$/, `.${options.outExtension}`);
const outDir = dirname(outPath);
if (!outDirs.includes(outDir)) {
outDirs.push(outDir);
}
foundFiles.push({
srcPath: srcFile,
outPath,
});
}
}
if (include) {
for (const pattern of include) {
const globFiles = await glob(join(absProject, pattern));
for (const file of globFiles) {
if (!file.endsWith(".ts") && !file.endsWith(".js")) {
continue;
}
if (file.endsWith(".d.ts")) {
continue;
}
const relativeFile = relative(absProject, file);
const outFile = join(options.outDirPath, relativeFile);
const outPath = outFile.replace(/\.\w+$/, `.${options.outExtension}`);
const outDir = dirname(outPath);
if (!outDirs.includes(outDir)) {
outDirs.push(outDir);
}
foundFiles.push({
srcPath: file,
outPath,
});
}
}
}
for (const outDirPath of outDirs) {
if (!(await exists(outDirPath))) {
await mkdir(outDirPath);
}
}
// TODO: read exclude
return foundFiles;
}
async function updateOptionsFromProject(options: CLIOptions): Promise<void> {
/**
* Read the project information and assign the following.
* - outDirPath
* - transform: imports
* - transform: typescript
* - enableLegacyTypescriptModuleInterop: true/false.
*/
const tsConfigPath = join(options.project, "tsconfig.json");
let str;
try {
str = await readFile(tsConfigPath, "utf8");
} catch (err) {
console.error("Could not find project tsconfig.json");
console.error(` --project=${options.project}`);
console.error(err);
process.exit(1);
}
const json = JSON.parse(str);
const sucraseOpts = options.sucraseOptions;
if (!sucraseOpts.transforms.includes("typescript")) {
sucraseOpts.transforms.push("typescript");
}
const compilerOpts = json.compilerOptions;
if (compilerOpts.outDir) {
options.outDirPath = join(process.cwd(), options.project, compilerOpts.outDir);
}
if (compilerOpts.esModuleInterop !== true) {
sucraseOpts.enableLegacyTypeScriptModuleInterop = true;
}
if (compilerOpts.module === "commonjs") {
if (!sucraseOpts.transforms.includes("imports")) {
sucraseOpts.transforms.push("imports");
}
}
}
async function buildDirectory(options: CLIOptions): Promise<void> {
let files: Array<FileInfo>;
if (options.outDirPath && options.srcDirPath) {
files = await findFiles(options);
} else if (options.project) {
await updateOptionsFromProject(options);
files = await runGlob(options);
} else {
console.error("Project or Source directory required.");
process.exit(1);
}
for (const file of files) {
await buildFile(file.srcPath, file.outPath, options);
}
}
async function buildFile(srcPath: string, outPath: string, options: CLIOptions): Promise<void> {
if (!options.quiet) {
console.log(`${srcPath} -> ${outPath}`);
}
const code = (await readFile(srcPath)).toString();
const transformedCode = transform(code, {...options.sucraseOptions, filePath: srcPath}).code;
await writeFile(outPath, transformedCode);
}