-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
/
scan.ts
248 lines (227 loc) · 6.63 KB
/
scan.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
import fs from 'fs'
import path from 'path'
import glob from 'fast-glob'
import { ResolvedConfig } from '..'
import { build, Loader, Plugin } from 'esbuild'
import { knownAssetTypes } from '../constants'
import {
createDebugger,
emptyDir,
isDataUrl,
isExternalUrl,
normalizePath
} from '../utils'
import { browserExternalId } from '../plugins/resolve'
import chalk from 'chalk'
import {
createPluginContainer,
PluginContainer
} from '../server/pluginContainer'
const debug = createDebugger('vite:scan')
export async function scanImports(
config: ResolvedConfig
): Promise<Record<string, string>> {
const s = Date.now()
const htmlEntries = await glob('**/index.html', {
cwd: config.root,
ignore: [
'**/node_modules/**',
`**/${config.build.outDir}/**`,
`**/__tests__/**`
],
absolute: true
})
const tempDir = path.join(config.optimizeCacheDir!, 'scan')
const depImports: Record<string, string> = {}
const missing = new Set<string>()
const plugin = esbuildScanPlugin(config, depImports, missing)
await Promise.all(
htmlEntries.map((entry) =>
build({
entryPoints: [entry],
bundle: true,
format: 'esm',
logLevel: 'error',
outdir: tempDir,
outbase: config.root,
plugins: [plugin]
})
)
)
emptyDir(tempDir)
fs.rmdirSync(tempDir)
debug(`scan completed in ${Date.now() - s}ms:`, depImports)
if (missing.size) {
config.logger.error(
`The following dependencies are imported but couldn't be resolved: ${[
...missing
].join(', ')}`
)
}
return depImports
}
const scriptModuleRE = /(<script\b[^>]*type\s*=\s*(?:"module"|'module')[^>]*>)(.*?)<\/script>/gims
const scriptRE = /(<script\b[^>]*>)(.*?)<\/script>/gims
const srcRE = /\bsrc\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im
const langRE = /\blang\s*=\s*(?:"([^"]+)"|'([^']+)'|([^\s'">]+))/im
function esbuildScanPlugin(
config: ResolvedConfig,
depImports: Record<string, string>,
missing: Set<string>
): Plugin {
let container: PluginContainer
const seen = new Map<string, string | undefined>()
const resolve = async (id: string, importer?: string) => {
const key = id + importer
if (seen.has(key)) {
return seen.get(key)
}
container = container || (container = await createPluginContainer(config))
const resolved = await container.resolveId(
id,
importer && normalizePath(importer)
)
const res = resolved?.id
seen.set(key, res)
return res
}
const include = config.optimizeDeps?.include
const exclude = config.optimizeDeps?.exclude
return {
name: 'vite:dep-scan',
setup(build) {
const htmlTypesRe = /\.(html|vue|svelte)$/
// html types: extract script contents
build.onResolve({ filter: htmlTypesRe }, async ({ path, importer }) => {
return {
path: await resolve(path, importer),
namespace: 'html'
}
})
build.onLoad(
{ filter: htmlTypesRe, namespace: 'html' },
async ({ path }) => {
const raw = await fs.promises.readFile(path, 'utf-8')
const regex = path.endsWith('.html') ? scriptModuleRE : scriptRE
regex.lastIndex = 0
let js = ''
let loader: Loader = 'js'
for (const [_, openTag, content] of raw.matchAll(regex)) {
const srcMatch = openTag.match(srcRE)
const langMatch = openTag.match(langRE)
const lang =
langMatch && (langMatch[1] || langMatch[2] || langMatch[3])
if (lang === 'ts') {
loader = 'ts'
}
if (srcMatch) {
const src = srcMatch[1] || srcMatch[2] || srcMatch[3]
js += `import ${JSON.stringify(src)}\n`
} else if (content.trim()) {
js += content + '\n'
}
}
if (!js.includes(`export default`)) {
js += `export default {}`
}
return {
loader,
contents: js
}
}
)
// css: externalize
build.onResolve(
{
filter: /\.(css|less|sass|scss|styl|stylus|postcss)$/
},
({ path }) => ({ path, external: true })
)
// known asset types: externalize
build.onResolve(
{
filter: new RegExp(`\\.(${knownAssetTypes.join('|')})$`)
},
({ path }) => ({ path, external: true })
)
// bare imports: record and externalize
build.onResolve(
{
// avoid matching windows volume
filter: /^[\w@][^:]/
},
async ({ path: id, importer }) => {
if (depImports[id]) {
return {
path: id,
external: true
}
}
if (isExternalUrl(id) || isDataUrl(id)) {
return {
path: id,
external: true
}
}
const resolved = await resolve(id, importer)
if (resolved) {
// browser external
if (resolved.startsWith(browserExternalId)) {
return { path: id, external: true }
}
// virtual id
if (id === resolved) {
return { path: id, external: true }
}
// dep or force included, externalize and stop crawling
if (resolved.includes('node_modules') || include?.includes(id)) {
if (!exclude?.includes(id)) {
depImports[id] = resolved
}
return {
path: id,
external: true
}
} else {
// linked package, keep crawling
return {
path: path.resolve(resolved)
}
}
} else {
config.logger.error(
chalk.red(
`Dependency ${id} not found. Is it installed? (imported by ${importer})`
)
)
missing.add(id)
}
}
)
// catch all
build.onResolve(
{
filter: /.*/
},
async ({ path: id, importer }) => {
if (id.includes(`?worker`)) {
return { path: id, external: true }
}
// use vite resolver to support urls
const resolved = await resolve(id, importer)
if (resolved && resolved !== id) {
return {
path: path.resolve(resolved)
}
} else {
// resolve failed... probably usupported type
return {
path: id,
external: true
}
}
}
)
}
}
}