-
-
Notifications
You must be signed in to change notification settings - Fork 367
/
Copy pathunplugin.ts
103 lines (91 loc) · 3.02 KB
/
unplugin.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
import { existsSync } from 'fs'
import { createUnplugin } from 'unplugin'
import { createFilter } from '@rollup/pluginutils'
import chokidar from 'chokidar'
import type { ResolvedConfig, ViteDevServer } from 'vite'
import type { Watching } from 'webpack'
import type { Options, PublicPluginAPI } from '../types'
import { Context } from './context'
import { shouldTransform, stringifyComponentImport } from './utils'
const PLUGIN_NAME = 'unplugin:webpack'
export default createUnplugin<Options>((options = {}) => {
const filter = createFilter(
options.include || [/\.vue$/, /\.vue\?vue/, /\.vue\?v=/],
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/],
)
const ctx: Context = new Context(options)
const api: PublicPluginAPI = {
async findComponent(name, filename) {
return await ctx.findComponent(name, 'component', filename ? [filename] : [])
},
stringifyImport(info) {
return stringifyComponentImport(info, ctx)
},
}
return {
name: 'unplugin-vue-components',
enforce: 'post',
api,
transformInclude(id) {
return filter(id)
},
async transform(code, id) {
if (!shouldTransform(code))
return null
try {
const result = await ctx.transform(code, id)
ctx.generateDeclaration()
return result
}
catch (e) {
this.error(e)
}
},
vite: {
configResolved(config: ResolvedConfig) {
ctx.setRoot(config.root)
ctx.sourcemap = true
if (config.plugins.find(i => i.name === 'vite-plugin-vue2'))
ctx.setTransformer('vue2')
if (ctx.options.dts) {
ctx.searchGlob()
if (!existsSync(ctx.options.dts))
ctx.generateDeclaration()
}
if (config.build.watch && config.command === 'build')
ctx.setupWatcher(chokidar.watch(ctx.options.globs))
},
configureServer(server: ViteDevServer) {
ctx.setupViteServer(server)
},
},
webpack(compiler) {
let watcher: Watching
let fileDepQueue: { path: string; type: 'unlink' | 'add' }[] = []
compiler.hooks.watchRun.tap(PLUGIN_NAME, () => {
// ensure watcher is ready(supported since webpack@5.0.0-rc.1)
if (!watcher && compiler.watching) {
watcher = compiler.watching
ctx.setupWatcherWebpack(chokidar.watch(ctx.options.globs), (path: string, type: 'unlink' | 'add') => {
fileDepQueue.push({ path, type })
// process.nextTick is for aggregated file change event
process.nextTick(() => {
watcher.invalidate()
})
})
}
})
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
if (fileDepQueue.length) {
fileDepQueue.forEach(({ path, type }) => {
if (type === 'unlink')
compilation.fileDependencies.delete(path)
else
compilation.fileDependencies.add(path)
})
fileDepQueue = []
}
})
},
}
})