-
-
Notifications
You must be signed in to change notification settings - Fork 43
/
index.ts
380 lines (338 loc) · 11 KB
/
index.ts
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
import _debug from 'debug'
import * as fs from 'fs'
import globRex from 'globrex'
import { resolve } from 'path'
import * as tsconfck from 'tsconfck'
import type { CompilerOptions } from 'typescript'
import { inspect } from 'util'
import { normalizePath, Plugin, searchForWorkspaceRoot } from 'vite'
import { resolvePathMappings } from './mappings'
import { basename, dirname, isAbsolute, join, relative } from './path'
import { PluginOptions } from './types'
const debug = _debug('vite-tsconfig-paths')
const noMatch = [undefined, false] as [undefined, false]
type ViteResolve = (id: string, importer: string) => Promise<string | undefined>
type Resolver = (
viteResolve: ViteResolve,
id: string,
importer: string
) => Promise<[resolved: string | undefined, matched: boolean]>
export type { PluginOptions }
export default (opts: PluginOptions = {}): Plugin => {
let resolversByDir: Record<string, Resolver[]>
return {
name: 'vite-tsconfig-paths',
enforce: 'pre',
async configResolved(config) {
let projectRoot = config.root
let workspaceRoot!: string
let { root } = opts
if (root) {
root = resolve(projectRoot, root)
} else {
workspaceRoot = searchForWorkspaceRoot(projectRoot)
}
debug('options.root ==', root)
debug('project root ==', projectRoot)
debug('workspace root ==', workspaceRoot)
// The "root" option overrides both of these.
if (root) {
projectRoot = root
workspaceRoot = root
}
const projects = await resolveProjectPaths(
opts.projects,
projectRoot,
workspaceRoot
)
debug('projects:', projects)
let hasTypeScriptDep = false
if (opts.parseNative) {
try {
const pkgJson = fs.readFileSync(
join(workspaceRoot, 'package.json'),
'utf8'
)
const pkg = JSON.parse(pkgJson)
const deps = { ...pkg.dependencies, ...pkg.devDependencies }
hasTypeScriptDep = 'typescript' in deps
} catch (e: any) {
if (e.code != 'ENOENT') {
throw e
}
}
}
const parsedProjects = new Set(
await Promise.all(
projects.map((tsconfigFile) =>
hasTypeScriptDep
? tsconfck.parseNative(tsconfigFile)
: tsconfck.parse(tsconfigFile)
)
)
)
resolversByDir = {}
parsedProjects.forEach((project) => {
// Don't create a resolver for projects with a references array.
// Instead, create a resolver for each project in that array.
if (project.referenced) {
project.referenced.forEach((projectRef) => {
parsedProjects.add(projectRef)
})
// Reinsert the parent project so it's tried last. This is
// important because project references can be used to
// override the parent project.
parsedProjects.delete(project)
parsedProjects.add(project)
project.referenced = undefined
} else {
const resolver = createResolver(project)
if (resolver) {
const projectDir = normalizePath(dirname(project.tsconfigFile))
const resolvers = (resolversByDir[projectDir] ||= [])
resolvers.push(resolver)
}
}
})
},
async resolveId(id, importer) {
if (importer && !relativeImportRE.test(id) && !isAbsolute(id)) {
const viteResolve: ViteResolve = async (id, importer) =>
(await this.resolve(id, importer, { skipSelf: true }))?.id
let prevProjectDir: string | undefined
let projectDir = dirname(importer)
// Find the nearest directory with a matching tsconfig file.
loop: while (projectDir && projectDir != prevProjectDir) {
const resolvers = resolversByDir[projectDir]
if (resolvers)
for (const resolve of resolvers) {
const [resolved, matched] = await resolve(
viteResolve,
id,
importer
)
if (resolved) {
return resolved
}
if (matched) {
// Once a matching resolver is found, stop looking.
break loop
}
}
prevProjectDir = projectDir
projectDir = dirname(prevProjectDir)
}
}
},
}
function createResolver(
project: tsconfck.TSConfckParseResult
): Resolver | null {
const configPath = normalizePath(project.tsconfigFile)
const config = project.tsconfig as {
files?: string[]
include?: string[]
exclude?: string[]
compilerOptions: CompilerOptions
}
debug('config loaded:', inspect({ configPath, config }, false, 10, true))
// Sometimes a tsconfig is not meant to be used for path resolution,
// but rather for pointing to other tsconfig files and possibly
// being extended by them. This is represented by an explicitly
// empty "files" array and a missing/empty "include" array.
if (config.files?.length == 0 && !config.include?.length) {
debug(
`[!] skipping "${configPath}" as no files can be matched since "files" is empty and "include" is missing or empty`
)
return null
}
const options = config.compilerOptions
const { baseUrl, paths } = options
if (!baseUrl && !paths) {
debug(`[!] missing baseUrl and paths: "${configPath}"`)
return null
}
type InternalResolver = (
viteResolve: ViteResolve,
id: string,
importer: string
) => Promise<string | undefined>
const resolveWithBaseUrl: InternalResolver | undefined = baseUrl
? (viteResolve, id, importer) => viteResolve(join(baseUrl, id), importer)
: undefined
let resolveId: InternalResolver
if (paths) {
const pathMappings = resolvePathMappings(
paths,
options.baseUrl ?? dirname(configPath)
)
const resolveWithPaths: InternalResolver = async (
viteResolve,
id,
importer
) => {
for (const mapping of pathMappings) {
const match = id.match(mapping.pattern)
if (!match) {
continue
}
for (let pathTemplate of mapping.paths) {
let starCount = 0
const mappedId = pathTemplate.replace(/\*/g, () => {
// There may exist more globs in the path template than in
// the match pattern. In that case, we reuse the final
// glob match.
const matchIndex = Math.min(++starCount, match.length - 1)
return match[matchIndex]
})
const resolved = await viteResolve(mappedId, importer)
if (resolved) {
return resolved
}
}
}
}
if (resolveWithBaseUrl) {
resolveId = (viteResolve, id, importer) =>
resolveWithPaths(viteResolve, id, importer).then((resolved) => {
return resolved ?? resolveWithBaseUrl(viteResolve, id, importer)
})
} else {
resolveId = resolveWithPaths
}
} else {
resolveId = resolveWithBaseUrl!
}
const configDir = dirname(configPath)
// When `tsconfck.parseNative` is used, the outDir is absolute,
// which is not what `getIncluder` expects.
let { outDir } = options
if (outDir && isAbsolute(outDir)) {
outDir = relative(configDir, outDir)
}
const isIncludedRelative = getIncluder(
config.include,
config.exclude,
outDir
)
const importerExtRE = opts.loose
? /./
: options.allowJs || basename(configPath).startsWith('jsconfig.')
? jsLikeRE
: /\.[mc]?tsx?$/
const resolutionCache = new Map<string, string>()
return async (viteResolve, id, importer) => {
// Skip virtual modules.
if (id.includes('\0')) {
return noMatch
}
importer = normalizePath(importer)
const importerFile = importer.replace(/[#?].+$/, '')
// Ignore importers with unsupported extensions.
if (!importerExtRE.test(importerFile)) {
return noMatch
}
// Respect the include/exclude properties.
const relativeImporterFile = relative(configDir, importerFile)
if (!isIncludedRelative(relativeImporterFile)) {
return noMatch
}
// Find and remove Vite's suffix (e.g. "?url") if present.
// If the path is resolved, the suffix will be added back.
const suffix = /\?.+$/.exec(id)?.[0]
if (suffix) {
id = id.slice(0, -suffix.length)
}
let path = resolutionCache.get(id)
if (!path) {
path = await resolveId(viteResolve, id, importer)
if (path) {
resolutionCache.set(id, path)
debug(`resolved:`, {
id,
importer,
resolvedId: path,
configPath,
})
}
}
return [path && suffix ? path + suffix : path, true]
}
}
}
const jsLikeRE = /\.(vue|svelte|mdx|[mc]?[jt]sx?)$/
const relativeImportRE = /^\.\.?(\/|$)/
const defaultInclude = ['**/*']
const defaultExclude = [
'**/node_modules',
'**/bower_components',
'**/jspm_packages',
]
/**
* The returned function does not support absolute paths.
* Be sure to call `path.relative` on your path first.
*/
function getIncluder(
includePaths = defaultInclude,
excludePaths = defaultExclude,
outDir?: string
) {
if (outDir) {
excludePaths = excludePaths.concat(outDir)
}
if (includePaths.length || excludePaths.length) {
const includers: RegExp[] = []
const excluders: RegExp[] = []
includePaths.forEach(addCompiledGlob, includers)
excludePaths.forEach(addCompiledGlob, excluders)
debug(`compiled globs:`, { includers, excluders })
return (path: string) => {
path = path.replace(/\?.+$/, '')
if (!relativeImportRE.test(path)) {
path = './' + path
}
const test = (glob: RegExp) => glob.test(path)
return includers.some(test) && !excluders.some(test)
}
}
return () => true
}
function addCompiledGlob(this: RegExp[], glob: string) {
const endsWithGlob = glob.split('/').pop()!.includes('*')
const relativeGlob = relativeImportRE.test(glob) ? glob : './' + glob
if (endsWithGlob) {
this.push(compileGlob(relativeGlob))
} else {
// Append a globstar to possible directories.
this.push(compileGlob(relativeGlob + '/**'))
// Try to match specific files (must have file extension).
if (/\.\w+$/.test(glob)) {
this.push(compileGlob(relativeGlob))
}
}
}
function compileGlob(glob: string) {
return globRex(glob, {
extended: true,
globstar: true,
}).regex
}
function resolveProjectPaths(
projects: string[] | undefined,
projectRoot: string,
workspaceRoot: string
) {
if (projects) {
return projects.map((file) => {
if (!file.endsWith('.json')) {
file = join(file, 'tsconfig.json')
}
return resolve(projectRoot, file)
})
}
return tsconfck.findAll(workspaceRoot, {
skip(dir) {
return dir == 'node_modules' || dir == '.git'
},
})
}