/
index.ts
54 lines (45 loc) · 1.19 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
import { start, destory } from './utils/file'
import schema from './utils/schema.json'
import { validate } from 'schema-utils'
import type { Compiler } from 'webpack'
import type { pluginOptions } from './type'
export const WebpackPlugin = class SvgPreviewPlugin {
isWatch = false
options: pluginOptions
constructor(options: pluginOptions) {
validate(schema as any, options, {
name: 'SvgPreviewPlugin',
baseDataPath: "options"
})
this.options = options
}
async apply(compiler: Compiler) {
const { options } = this
options.open ??= true
options.port ??= 3000
compiler.hooks.done.tap('SvgPreviewPlugin', ()=> {
console.log(`SVG预览:`, `\x1B[36mhttp://localhost:${options.port}\x1B[0m`)
})
compiler.hooks.watchClose.tap('SvgPreviewPlugin', destory)
if (!this.isWatch) {
this.isWatch = true
await start(options)
}
}
}
export function VitePlugin (options: pluginOptions) {
options.open ??= true
options.port ??= 3000
return {
name: 'SvgPreviewPlugin',
apply: 'serve',
async buildStart() {
console.log(`SVG预览:`, `\x1B[36mhttp://localhost:${options.port}\x1B[0m`)
destory()
await start(options)
},
closeWatcher() {
destory()
}
}
}