config-loader.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import * as TsConfigLoader2 from "./tsconfig-loader";
  2. import * as path from "path";
  3. import { options } from "./options";
  4. export interface ExplicitParams {
  5. baseUrl: string;
  6. paths: { [key: string]: Array<string> };
  7. mainFields?: Array<string>;
  8. addMatchAll?: boolean;
  9. }
  10. export type TsConfigLoader = (
  11. params: TsConfigLoader2.TsConfigLoaderParams
  12. ) => TsConfigLoader2.TsConfigLoaderResult;
  13. export interface ConfigLoaderParams {
  14. cwd: string;
  15. explicitParams?: ExplicitParams;
  16. tsConfigLoader?: TsConfigLoader;
  17. }
  18. export interface ConfigLoaderSuccessResult {
  19. resultType: "success";
  20. configFileAbsolutePath: string;
  21. baseUrl: string;
  22. absoluteBaseUrl: string;
  23. paths: { [key: string]: Array<string> };
  24. mainFields?: Array<string>;
  25. addMatchAll?: boolean;
  26. }
  27. export interface ConfigLoaderFailResult {
  28. resultType: "failed";
  29. message: string;
  30. }
  31. export type ConfigLoaderResult =
  32. | ConfigLoaderSuccessResult
  33. | ConfigLoaderFailResult;
  34. export function loadConfig(cwd: string = options.cwd): ConfigLoaderResult {
  35. return configLoader({ cwd: cwd });
  36. }
  37. export function configLoader({
  38. cwd,
  39. explicitParams,
  40. tsConfigLoader = TsConfigLoader2.tsConfigLoader,
  41. }: ConfigLoaderParams): ConfigLoaderResult {
  42. if (explicitParams) {
  43. // tslint:disable-next-line:no-shadowed-variable
  44. const absoluteBaseUrl = path.isAbsolute(explicitParams.baseUrl)
  45. ? explicitParams.baseUrl
  46. : path.join(cwd, explicitParams.baseUrl);
  47. return {
  48. resultType: "success",
  49. configFileAbsolutePath: "",
  50. baseUrl: explicitParams.baseUrl,
  51. absoluteBaseUrl,
  52. paths: explicitParams.paths,
  53. mainFields: explicitParams.mainFields,
  54. addMatchAll: explicitParams.addMatchAll,
  55. };
  56. }
  57. // Load tsconfig and create path matching function
  58. const loadResult = tsConfigLoader({
  59. cwd,
  60. getEnv: (key: string) => process.env[key],
  61. });
  62. if (!loadResult.tsConfigPath) {
  63. return {
  64. resultType: "failed",
  65. message: "Couldn't find tsconfig.json",
  66. };
  67. }
  68. if (!loadResult.baseUrl) {
  69. return {
  70. resultType: "failed",
  71. message: "Missing baseUrl in compilerOptions",
  72. };
  73. }
  74. const tsConfigDir = path.dirname(loadResult.tsConfigPath);
  75. const absoluteBaseUrl = path.join(tsConfigDir, loadResult.baseUrl);
  76. return {
  77. resultType: "success",
  78. configFileAbsolutePath: loadResult.tsConfigPath,
  79. baseUrl: loadResult.baseUrl,
  80. absoluteBaseUrl,
  81. paths: loadResult.paths || {},
  82. };
  83. }