-
-
Notifications
You must be signed in to change notification settings - Fork 217
Expand file tree
/
Copy pathunplugin.ts
More file actions
73 lines (64 loc) · 1.92 KB
/
Copy pathunplugin.ts
File metadata and controls
73 lines (64 loc) · 1.92 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
import type { FilterPattern } from 'unplugin'
import type { Options } from '../types'
import { slash } from '@antfu/utils'
import { isPackageExists } from 'local-pkg'
import { createUnplugin } from 'unplugin'
import { createContext, EXCLUDE_RE_LIST, INCLUDE_RE_LIST } from './ctx'
export default createUnplugin<Options>((options) => {
let ctx = createContext(options)
return {
name: 'unplugin-auto-import',
enforce: 'post',
transformInclude(id) {
return ctx.filter(id)
},
transform: {
filter: {
id: {
include: options.include as FilterPattern || INCLUDE_RE_LIST,
exclude: options.exclude as FilterPattern || EXCLUDE_RE_LIST,
},
},
async handler(code, id) {
return ctx.transform(code, id)
},
},
async buildStart() {
await ctx.scanDirs()
},
async buildEnd() {
await ctx.writeConfigFiles()
},
vite: {
async config(config) {
if (options.viteOptimizeDeps === false)
return
const exclude = config.optimizeDeps?.exclude || []
const imports = new Set((await ctx.unimport.getImports()).map(i => i.from).filter(i => i.match(/^[a-z@]/) && !exclude.includes(i) && isPackageExists(i)))
if (!imports.size)
return
return {
optimizeDeps: {
include: [...imports],
},
}
},
async handleHotUpdate({ file }) {
if (!ctx.dirs?.length)
return
if (ctx.configFilePaths.includes(file))
return
const normalizedFilePath = slash(file)
const shouldRescan = ctx.normalizedDirMatchers.some(match => match(normalizedFilePath))
if (shouldRescan)
await ctx.scanDirs()
},
async configResolved(config) {
if (ctx.root !== config.root) {
ctx = createContext(options, config.root)
await ctx.scanDirs()
}
},
},
}
})