8000 fix: tsconfig baseURL and automatic alias · fuse-box/fuse-box@3d7e228 · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content
This repository was archived by the owner on Jun 20, 2023. It is now read-only.

Commit 3d7e228

Browse files
committed
fix: tsconfig baseURL and automatic alias
1 parent 6644a97 commit 3d7e228

File tree

1 file changed

+88
-100
lines changed

1 file changed

+88
-100
lines changed

src/core/TypescriptConfig.ts

Lines changed: 88 additions & 100 deletions
Original file line numberDiff line numberDiff line change
@@ -18,40 +18,35 @@ const CACHED: { [path: string]: any } = {};
1818
* e.g:
1919
* - Instead of `target: 1`, user can input `target: 'ES5'`
2020
*/
21-
export type rawScriptTarget = Exclude<keyof typeof ts.ScriptTarget, "JSON" | "Latest">
21+
export type rawScriptTarget = Exclude<keyof typeof ts.ScriptTarget, "JSON" | "Latest">;
2222
export type rawCompilerOptions = {
23-
[key in keyof ts.CompilerOptions]: (
24-
key extends "maxNodeModuleJsDepth"
23+
[key in keyof ts.CompilerOptions]: key extends "maxNodeModuleJsDepth"
2524
? number
2625
: ts.CompilerOptions[key] extends ts.ScriptTarget
27-
? rawScriptTarget
28-
: ts.CompilerOptions[key] extends ts.JsxEmit
29-
? "react" | "preserve" | "react-native"
30-
: ts.CompilerOptions[key] extends ts.ModuleKind
31-
? keyof typeof ts.ModuleKind
32-
: ts.CompilerOptions[key] extends ts.ModuleResolutionKind
33-
? keyof typeof ts.ModuleResolutionKind
34-
: ts.CompilerOptions[key] extends ts.NewLineKind
35-
? "CRLF" | "LF"
36-
: ts.CompilerOptions[key] extends ts.MapLike<string[]>
37-
? ts.MapLike<string[]>
38-
: ts.CompilerOptions[key] extends string[]
39-
? string[]
40-
: ts.CompilerOptions[key] extends string
41-
? ts.CompilerOptions[key]
42-
: ts.CompilerOptions[key] extends boolean
43-
? ts.CompilerOptions[key]
44-
: ts.CompilerOptions[key] extends number
45-
? number
46-
: any
47-
)
48-
}
26+
? rawScriptTarget
27+
: ts.CompilerOptions[key] extends ts.JsxEmit
28+
? "react" | "preserve" | "react-native"
29+
: ts.CompilerOptions[key] extends ts.ModuleKind
30+
? keyof typeof ts.ModuleKind
31+
: ts.CompilerOptions[key] extends ts.ModuleResolutionKind
32+
? keyof typeof ts.ModuleResolutionKind
33+
: ts.CompilerOptions[key] extends ts.NewLineKind
34+
? "CRLF" | "LF"
35+
: ts.CompilerOptions[key] extends ts.MapLike<string[]>
36+
? ts.MapLike<string[]>
37+
: ts.CompilerOptions[key] extends string[]
38+
? string[]
39+
: ts.CompilerOptions[key] extends string
40+
? ts.CompilerOptions[key]
41+
: ts.CompilerOptions[key] extends boolean
42+
? ts.CompilerOptions[key]
43+
: ts.CompilerOptions[key] extends number ? number : any
44+
};
4945

5046
export function getScriptLevelNumber(level: any): ScriptTarget & number | undefined {
5147
if (Number.isNaN(Number(level)) && typeof level === "string") {
52-
const key = Object
53-
.keys(ScriptTarget)
54-
.filter(k => !['json', 'latest'].includes(k.toLowerCase()))
48+
const key = Object.keys(ScriptTarget)
49+
.filter(k => !["json", "latest"].includes(k.toLowerCase()))
5550
.find(t => t.toLowerCase() === level.toLowerCase());
5651
return key ? ScriptTarget[key] : undefined;
5752
}
@@ -62,29 +57,28 @@ export function getScriptLevelNumber(level: any): ScriptTarget & number | undefi
6257

6358
export function getScriptLevelString(level: any): rawScriptTarget | undefined {
6459
if (Number(level) in ScriptTarget) {
65-
const key = Object
66-
.keys(ScriptTarget)
67-
.filter(k => !['json', 'latest'].includes(k.toLowerCase()))
60+
const key = Object.keys(ScriptTarget)
61+
.filter(k => !["json", "latest"].includes(k.toLowerCase()))
6862
.find(t => ScriptTarget[t] === Number(level));
6963
return key as rawScriptTarget;
7064
}
7165
}
7266

7367
export interface ICategorizedDiagnostics {
74-
errors: ReadonlyArray<ts.Diagnostic & { category: ts.DiagnosticCategory.Error }>,
75-
warnings: ReadonlyArray<ts.Diagnostic & { category: ts.DiagnosticCategory.Warning }>,
76-
messages: ReadonlyArray<ts.Diagnostic & { category: ts.DiagnosticCategory.Message }>,
77-
suggestions: ReadonlyArray<ts.Diagnostic & { category: ts.DiagnosticCategory.Suggestion }>,
68+
errors: ReadonlyArray<ts.Diagnostic & { category: ts.DiagnosticCategory.Error }>;
69+
warnings: ReadonlyArray<ts.Diagnostic & { category: ts.DiagnosticCategory.Warning }>;
70+
messages: ReadonlyArray<ts.Diagnostic & { category: ts.DiagnosticCategory.Message }>;
71+
suggestions: ReadonlyArray<ts.Diagnostic & { category: ts.DiagnosticCategory.Suggestion }>;
7872
}
7973

8074
export interface TSParsedConfig {
81-
errors: Array<ts.Diagnostic | ts.DiagnosticWithLocation> | ts.SortedReadonlyArray<ts.Diagnostic>,
82-
compilerOptions: ts.CompilerOptions,
83-
compileOnSave?: boolean,
84-
projectReferences?: ReadonlyArray<ts.ProjectReference>,
85-
raw?: rawCompilerOptions,
86-
typeAcquisition?: ts.TypeAcquisition,
87-
wildcardDirectories?: ts.MapLike<ts.WatchDirectoryFlags>,
75+
errors: Array<ts.Diagnostic | ts.DiagnosticWithLocation> | ts.SortedReadonlyArray<ts.Diagnostic>;
76+
compilerOptions: ts.CompilerOptions;
77+
compileOnSave?: boolean;
78+
projectReferences?: ReadonlyArray<ts.ProjectReference>;
79+
raw?: rawCompilerOptions;
80+
typeAcquisition?: ts.TypeAcquisition;
81+
wildcardDirectories?: ts.MapLike<ts.WatchDirectoryFlags>;
8882
}
8983

9084
export const IGNORED_DIAGNOSTICS = new Set([
@@ -100,7 +94,7 @@ export function makePathDoesNotExistDiagnostic(path: string): ts.Diagnostic {
10094
file: undefined,
10195
length: undefined,
10296
start: undefined,
103-
}
97+
};
10498
}
10599

106100
export class TypescriptConfig {
@@ -114,7 +108,7 @@ export class TypescriptConfig {
114108
getCanonicalFileName: file => file,
115109
getCurrentDirectory: () => context.homeDir,
116110
getNewLine: () => ts.sys.newLine,
117-
}
111+
};
118112
}
119113

120114
public getConfig() {
@@ -123,7 +117,7 @@ export class TypescriptConfig {
123117
}
124118

125119
public normalizeDiagnostics(diagnostics: ts.Diagnostic[]): ts.SortedReadonlyArray<ts.Diagnostic> {
126-
return ts.sortAndDeduplicateDiagnostics(diagnostics.filter(x => !IGNORED_DIAGNOSTICS.has(x.code)))
120+
return ts.sortAndDeduplicateDiagnostics(diagnostics.filter(x => !IGNORED_DIAGNOSTICS.has(x.code)));
127121
}
128122

129123
private findConfigFileBackwards(tsConfigFilePath: string): string {
@@ -133,16 +127,15 @@ export class TypescriptConfig {
133127
public readJsonConfigFile(): TSParsedConfig {
134128
const config: TSParsedConfig = { compilerOptions: {}, errors: [] };
135129

136-
this.configFile = (
130+
this.configFile =
137131
typeof this.customTsConfig === "string"
138132
? ensureUserPath(this.customTsConfig)
139-
: this.findConfigFileBackwards(path.join(this.context.homeDir, "tsconfig.json"))
140-
);
133+
: this.findConfigFileBackwards(path.join(this.context.homeDir, "tsconfig.json"));
141134

142135
if (this.configFile) {
143136
if (!ts.sys.fileExists(this.configFile)) {
144137
config.errors = [makePathDoesNotExistDiagnostic(this.configFile)];
145-
return config
138+
return config;
146139
}
147140
const configFileRelPath = this.configFile.replace(this.context.appRoot, "");
148141
this.context.log.echoInfo(`Typescript config file: ${configFileRelPath}`);
@@ -167,7 +160,7 @@ export class TypescriptConfig {
167160
JSONSourceFile,
168161
ts.sys,
169162
path.dirname(this.configFile),
170-
)
163+
);
171164
if (parsedJSONConfigFile.errors.length) {
172165
const errors = this.normalizeDiagnostics(parsedJSONConfigFile.errors);
173166
if (errors.length) {
@@ -176,41 +169,34 @@ export class TypescriptConfig {
176169
}
177170
}
178171

179-
Object.assign(
180-
config,
181-
{
182-
compilerOptions: parsedJSONConfigFile.options,
183-
compileOnSave: parsedJSONConfigFile.compileOnSave,
184-
projectReferences: parsedJSONConfigFile.projectReferences,
185-
raw: parsedJSONConfigFile.raw,
186-
typeAcquisition: parsedJSONConfigFile.typeAcquisition,
187-
wildcardDirectories: parsedJSONConfigFile.wildcardDirectories,
188-
},
189-
);
172+
Object.assign(config, {
173+
compilerOptions: parsedJSONConfigFile.options,
174+
compileOnSave: parsedJSONConfigFile.compileOnSave,
175+
projectReferences: parsedJSONConfigFile.projectReferences,
176+
raw: parsedJSONConfigFile.raw,
177+
typeAcquisition: parsedJSONConfigFile.typeAcquisition,
178+
wildcardDirectories: parsedJSONConfigFile.wildcardDirectories,
179+
});
190180
}
191181

192182
if (Array.isArray(this.customTsConfig)) {
193183
const tsConfigOverrideCompilerOptions = {};
194184
this.customTsConfig.forEach(config => {
195-
if (
196-
typeof config === "object" &&
197-
config !== null
198-
) {
185+
if (typeof config === "object" && config !== null) {
199186
Object.assign(tsConfigOverrideCompilerOptions, config);
200-
} else { /** TODO! unknown type */ }
187+
} else {
188+
/** TODO! unknown type */
189+
}
201190
});
202191

203192
const parsedVirtualJSONConfig = ts.convertCompilerOptionsFromJson(
204193
tsConfigOverrideCompilerOptions,
205194
config.compilerOptions.baseUrl || ".",
206-
""
207-
);
208-
const virtualJSONSourceFile = ts.parseJsonText(
209-
"[FuseBoxOptions.tsConfig]",
210-
JSON.stringify(this.customTsConfig)
195+
"",
211196
);
197+
const virtualJSONSourceFile = ts.parseJsonText("[FuseBoxOptions.tsConfig]", JSON.stringify(this.customTsConfig));
212198

213-
const errors = this.normalizeDiagnostics(parsedVirtualJSONConfig.errors)
199+
const errors = this.normalizeDiagnostics(parsedVirtualJSONConfig.errors);
214200
if (errors.length) {
215201
const flattenError = errors[0];
216202
flattenError.file = virtualJSONSourceFile;
@@ -219,7 +205,7 @@ export class TypescriptConfig {
219205

220206
for (let i = 1; i < errors.length; i++) {
221207
const error = errors[i];
222-
flattenError.messageText += '\n' + this.formatDiagnostic(error, false);
208+
flattenError.messageText += "\n" + this.formatDiagnostic(error, false);
223209
}
224210

225211
config.errors = [flattenError];
@@ -241,14 +227,14 @@ export class TypescriptConfig {
241227
this.context.fuse.producer.allowSyntheticDefaultImports = config.compilerOptions.allowSyntheticDefaultImports;
242228
}
243229

244-
return config
230+
return config;
245231
}
246232

247233
private defaultSetup() {
248234
const compilerOptions = (this.config.compilerOptions = this.config.compilerOptions || {});
249235

250-
if (this.configFile && path.basename(this.configFile).startsWith('jsconfig.')) {
251-
compilerOptions.allowJs = true
236+
if (this.configFile && path.basename(this.configFile).startsWith("jsconfig.")) {
237+
compilerOptions.allowJs = true;
252238
}
253239
compilerOptions.sourceMap = this.context.useSourceMaps;
254240
compilerOptions.inlineSources = this.context.useSourceMaps;
@@ -257,10 +243,15 @@ export class TypescriptConfig {
257243
this.forceCompilerTarget(this.context.forcedLanguageLevel);
258244
}
259245

260-
if (compilerOptions.baseUrl === "." && this.context.automaticAlias) {
246+
const isValidBaseURL = compilerOptions.baseUrl === "." || compilerOptions.baseUrl === this.context.homeDir;
247+
if (isValidBaseURL && this.context.automaticAlias) {
261248
let aliasConfig = {};
262249
let log = [];
263250
fs.readdirSync(this.context.homeDir).forEach(file => {
251+
// skip files that start with .
252+
if (file[0] === ".") {
253+
return;
254+
}
264255
const extension = path.extname(file);
265256
if (!extension || extension === ".ts" || extension === ".tsx") {
266257
let name = file;
@@ -291,11 +282,11 @@ export class TypescriptConfig {
291282
if (!this.configFile && this.context.ensureTsConfig === true) {
292283
Object.assign(this.config.compilerOptions, {
293284
jsx: ts.JsxEmit.React,
294-
baseUrl: '.',
285+
baseUrl: ".",
295286
importHelpers: true,
296287
emitDecoratorMetadata: true,
297288
experimentalDecorators: true,
298-
})
289+
});
299290
// Raw compiler options
300291
const compilerOptions: rawCompilerOptions = Object.assign({}, this.config.compilerOptions as any, {
301292
target: getScriptLevelString(this.config.compilerOptions.target),
@@ -319,14 +310,14 @@ export class TypescriptConfig {
319310
}
320311
}
321312

322-
public categorizeDiagnostics(diagnostics: ReadonlyArray<ts.Diagnostic> | Readonly<ts.Diagnostic>): ICategorizedDiagnostics {
313+
public categorizeDiagnostics(
314+
diagnostics: ReadonlyArray<ts.Diagnostic> | Readonly<ts.Diagnostic>,
315+
): ICategorizedDiagnostics {
323316
const errors = [];
324317
const warnings = [];
325318
const messages = [];
326319
const suggestions = [];
327-
const diagnosticsArray = Array.isArray(diagnostics)
328-
? diagnostics
329-
: [diagnostics];
320+
const diagnosticsArray = Array.isArray(diagnostics) ? diagnostics : [diagnostics];
330321
const size = diagnosticsArray.length;
331322
for (let i = 0; i < size; i++) {
332323
const diagnostic: ts.Diagnostic = diagnosticsArray[i];
@@ -357,26 +348,24 @@ export class TypescriptConfig {
357348

358349
public formatDiagnostic(diagnostic: ts.Diagnostic, separator: boolean = true): string {
359350
// TODO! make a custom formatter instead
360-
diagnostic.messageText = `${diagnostic.messageText}\n`
361-
const formatted = ts.formatDiagnosticsWithColorAndContext(
362-
[diagnostic],
363-
this.formatDiagnosticsHost,
364-
)
351+
diagnostic.messageText = `${diagnostic.messageText}\n`;
352+
const formatted = ts
353+
.formatDiagnosticsWithColorAndContext([diagnostic], this.formatDiagnosticsHost)
365354
.replace(/error|warning|message/, match => match.toUpperCase())
366-
.replace(/ - /, '\n')
367-
.split('\n')
355+
.replace(/ - /, "\n")
356+
.split("\n")
368357
.filter(m => String(m).trim().length)
369-
.map((line, i) => i === 0 ? line : separator ? ` │ ${line}` : line)
370-
.join('\n')
358+
.map((line, i) => (i === 0 ? line : separator ? ` │ ${line}` : line))
359+
.join("\n");
371360

372-
return formatted
361+
return formatted;
373362
}
374363

375364
public logDiagnosticsByCategory(diagnostics: ReadonlyArray<ts.Diagnostic>, category: ts.DiagnosticCategory): void {
376365
if (diagnostics.length) {
377-
const size = diagnostics.length
366+
const size = diagnostics.length;
378367
for (let i = 0; i < size; i++) {
379-
const diagnosticMsg = this.formatDiagnostic(diagnostics[i])
368+
const diagnosticMsg = this.formatDiagnostic(diagnostics[i]);
380369
switch (category) {
381370
case ts.DiagnosticCategory.Error: {
382371
this.context.log.echoRed(` → ${diagnosticMsg}`);
@@ -414,11 +403,10 @@ export class TypescriptConfig {
414403
}
415404

416405
public read() {
417-
const cacheKey = (
418-
typeof this.customTsConfig === "string"
419-
? this.customTsConfig
420-
: this.context.homeDir
421-
) + this.context.target + this.context.languageLevel;
406+
const cacheKey =
407+
(typeof this.customTsConfig === "string" ? this.customTsConfig : this.context.homeDir) +
408+
this.context.target +
409+
this.context.languageLevel;
422410

423411
if (CACHED[cacheKey]) {
424412
this.config = CACHED[cacheKey];

0 commit comments

Comments
 (0)
0