tsconfig-loader.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  1. import * as path from "path";
  2. import * as fs from "fs";
  3. // tslint:disable:no-require-imports
  4. import JSON5 = require("json5");
  5. import StripBom = require("strip-bom");
  6. // tslint:enable:no-require-imports
  7. /**
  8. * Typing for the parts of tsconfig that we care about
  9. */
  10. export interface Tsconfig {
  11. extends?: string | string[];
  12. compilerOptions?: {
  13. baseUrl?: string;
  14. paths?: { [key: string]: Array<string> };
  15. strict?: boolean;
  16. };
  17. }
  18. export interface TsConfigLoaderResult {
  19. tsConfigPath: string | undefined;
  20. baseUrl: string | undefined;
  21. paths: { [key: string]: Array<string> } | undefined;
  22. }
  23. export interface TsConfigLoaderParams {
  24. getEnv: (key: string) => string | undefined;
  25. cwd: string;
  26. loadSync?(
  27. cwd: string,
  28. filename?: string,
  29. baseUrl?: string
  30. ): TsConfigLoaderResult;
  31. }
  32. export function tsConfigLoader({
  33. getEnv,
  34. cwd,
  35. loadSync = loadSyncDefault,
  36. }: TsConfigLoaderParams): TsConfigLoaderResult {
  37. const TS_NODE_PROJECT = getEnv("TS_NODE_PROJECT");
  38. const TS_NODE_BASEURL = getEnv("TS_NODE_BASEURL");
  39. // tsconfig.loadSync handles if TS_NODE_PROJECT is a file or directory
  40. // and also overrides baseURL if TS_NODE_BASEURL is available.
  41. const loadResult = loadSync(cwd, TS_NODE_PROJECT, TS_NODE_BASEURL);
  42. return loadResult;
  43. }
  44. function loadSyncDefault(
  45. cwd: string,
  46. filename?: string,
  47. baseUrl?: string
  48. ): TsConfigLoaderResult {
  49. // Tsconfig.loadSync uses path.resolve. This is why we can use an absolute path as filename
  50. const configPath = resolveConfigPath(cwd, filename);
  51. if (!configPath) {
  52. return {
  53. tsConfigPath: undefined,
  54. baseUrl: undefined,
  55. paths: undefined,
  56. };
  57. }
  58. const config = loadTsconfig(configPath);
  59. return {
  60. tsConfigPath: configPath,
  61. baseUrl:
  62. baseUrl ||
  63. (config && config.compilerOptions && config.compilerOptions.baseUrl),
  64. paths: config && config.compilerOptions && config.compilerOptions.paths,
  65. };
  66. }
  67. function resolveConfigPath(cwd: string, filename?: string): string | undefined {
  68. if (filename) {
  69. const absolutePath = fs.lstatSync(filename).isDirectory()
  70. ? path.resolve(filename, "./tsconfig.json")
  71. : path.resolve(cwd, filename);
  72. return absolutePath;
  73. }
  74. if (fs.statSync(cwd).isFile()) {
  75. return path.resolve(cwd);
  76. }
  77. const configAbsolutePath = walkForTsConfig(cwd);
  78. return configAbsolutePath ? path.resolve(configAbsolutePath) : undefined;
  79. }
  80. export function walkForTsConfig(
  81. directory: string,
  82. existsSync: (path: string) => boolean = fs.existsSync
  83. ): string | undefined {
  84. const configPath = path.join(directory, "./tsconfig.json");
  85. if (existsSync(configPath)) {
  86. return configPath;
  87. }
  88. const parentDirectory = path.join(directory, "../");
  89. // If we reached the top
  90. if (directory === parentDirectory) {
  91. return undefined;
  92. }
  93. return walkForTsConfig(parentDirectory, existsSync);
  94. }
  95. export function loadTsconfig(
  96. configFilePath: string,
  97. existsSync: (path: string) => boolean = fs.existsSync,
  98. readFileSync: (filename: string) => string = (filename: string) =>
  99. fs.readFileSync(filename, "utf8")
  100. ): Tsconfig | undefined {
  101. if (!existsSync(configFilePath)) {
  102. return undefined;
  103. }
  104. const configString = readFileSync(configFilePath);
  105. const cleanedJson = StripBom(configString);
  106. let config: Tsconfig;
  107. try {
  108. config = JSON5.parse(cleanedJson);
  109. } catch (e) {
  110. throw new Error(`${configFilePath} is malformed ${e.message}`);
  111. }
  112. let extendedConfig = config.extends;
  113. if (extendedConfig) {
  114. let base: Tsconfig;
  115. if (Array.isArray(extendedConfig)) {
  116. base = extendedConfig.reduce(
  117. (currBase, extendedConfigElement) =>
  118. mergeTsconfigs(
  119. currBase,
  120. loadTsconfigFromExtends(
  121. configFilePath,
  122. extendedConfigElement,
  123. existsSync,
  124. readFileSync
  125. )
  126. ),
  127. {}
  128. );
  129. } else {
  130. base = loadTsconfigFromExtends(
  131. configFilePath,
  132. extendedConfig,
  133. existsSync,
  134. readFileSync
  135. );
  136. }
  137. return mergeTsconfigs(base, config);
  138. }
  139. return config;
  140. }
  141. /**
  142. * Intended to be called only from loadTsconfig.
  143. * Parameters don't have defaults because they should use the same as loadTsconfig.
  144. */
  145. function loadTsconfigFromExtends(
  146. configFilePath: string,
  147. extendedConfigValue: string,
  148. // eslint-disable-next-line no-shadow
  149. existsSync: (path: string) => boolean,
  150. readFileSync: (filename: string) => string
  151. ): Tsconfig {
  152. if (
  153. typeof extendedConfigValue === "string" &&
  154. extendedConfigValue.indexOf(".json") === -1
  155. ) {
  156. extendedConfigValue += ".json";
  157. }
  158. const currentDir = path.dirname(configFilePath);
  159. let extendedConfigPath = path.join(currentDir, extendedConfigValue);
  160. if (
  161. extendedConfigValue.indexOf("/") !== -1 &&
  162. extendedConfigValue.indexOf(".") !== -1 &&
  163. !existsSync(extendedConfigPath)
  164. ) {
  165. extendedConfigPath = path.join(
  166. currentDir,
  167. "node_modules",
  168. extendedConfigValue
  169. );
  170. }
  171. const config =
  172. loadTsconfig(extendedConfigPath, existsSync, readFileSync) || {};
  173. // baseUrl should be interpreted as relative to extendedConfigPath,
  174. // but we need to update it so it is relative to the original tsconfig being loaded
  175. if (config.compilerOptions?.baseUrl) {
  176. const extendsDir = path.dirname(extendedConfigValue);
  177. config.compilerOptions.baseUrl = path.join(
  178. extendsDir,
  179. config.compilerOptions.baseUrl
  180. );
  181. }
  182. return config;
  183. }
  184. function mergeTsconfigs(
  185. base: Tsconfig | undefined,
  186. config: Tsconfig | undefined
  187. ): Tsconfig {
  188. base = base || {};
  189. config = config || {};
  190. return {
  191. ...base,
  192. ...config,
  193. compilerOptions: {
  194. ...base.compilerOptions,
  195. ...config.compilerOptions,
  196. },
  197. };
  198. }