Sin descripción

cli.js 10KB

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