config-loader.ts
2.41 KB
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
import * as TsConfigLoader2 from "./tsconfig-loader";
import * as path from "path";
import { options } from "./options";
export interface ExplicitParams {
baseUrl: string;
paths: { [key: string]: Array<string> };
mainFields?: Array<string>;
addMatchAll?: boolean;
}
export type TsConfigLoader = (
params: TsConfigLoader2.TsConfigLoaderParams
) => TsConfigLoader2.TsConfigLoaderResult;
export interface ConfigLoaderParams {
cwd: string;
explicitParams?: ExplicitParams;
tsConfigLoader?: TsConfigLoader;
}
export interface ConfigLoaderSuccessResult {
resultType: "success";
configFileAbsolutePath: string;
baseUrl: string;
absoluteBaseUrl: string;
paths: { [key: string]: Array<string> };
mainFields?: Array<string>;
addMatchAll?: boolean;
}
export interface ConfigLoaderFailResult {
resultType: "failed";
message: string;
}
export type ConfigLoaderResult =
| ConfigLoaderSuccessResult
| ConfigLoaderFailResult;
export function loadConfig(cwd: string = options.cwd): ConfigLoaderResult {
return configLoader({ cwd: cwd });
}
export function configLoader({
cwd,
explicitParams,
tsConfigLoader = TsConfigLoader2.tsConfigLoader,
}: ConfigLoaderParams): ConfigLoaderResult {
if (explicitParams) {
// tslint:disable-next-line:no-shadowed-variable
const absoluteBaseUrl = path.isAbsolute(explicitParams.baseUrl)
? explicitParams.baseUrl
: path.join(cwd, explicitParams.baseUrl);
return {
resultType: "success",
configFileAbsolutePath: "",
baseUrl: explicitParams.baseUrl,
absoluteBaseUrl,
paths: explicitParams.paths,
mainFields: explicitParams.mainFields,
addMatchAll: explicitParams.addMatchAll,
};
}
// Load tsconfig and create path matching function
const loadResult = tsConfigLoader({
cwd,
getEnv: (key: string) => process.env[key],
});
if (!loadResult.tsConfigPath) {
return {
resultType: "failed",
message: "Couldn't find tsconfig.json",
};
}
if (!loadResult.baseUrl) {
return {
resultType: "failed",
message: "Missing baseUrl in compilerOptions",
};
}
const tsConfigDir = path.dirname(loadResult.tsConfigPath);
const absoluteBaseUrl = path.join(tsConfigDir, loadResult.baseUrl);
return {
resultType: "success",
configFileAbsolutePath: loadResult.tsConfigPath,
baseUrl: loadResult.baseUrl,
absoluteBaseUrl,
paths: loadResult.paths || {},
};
}