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