-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathtransformPlugin.ts
More file actions
75 lines (65 loc) · 2.11 KB
/
Copy pathtransformPlugin.ts
File metadata and controls
75 lines (65 loc) · 2.11 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
74
75
import { createUnplugin } from 'unplugin'
import MagicString from 'magic-string'
import type { NuxtOptions } from '@nuxt/schema'
import { createResolver } from '@nuxt/kit'
import { allImportsWithStyle, libraryName } from '../config'
import { camelize, genSideEffectsImport, toRegExp } from '../utils'
import type { TransformOptions } from '../types'
interface PluginOptions extends TransformOptions {
layers: string[]
sourcemap?: NuxtOptions['sourcemap']['client']
transformStyles: (name: string) => undefined | string
}
const componentsRegExp =
/(?<=[ (])_?resolveComponent\(\s*["'](lazy-|Lazy)?([^'"]*?)["'][\s,]*[^)]*\)/g
const importsRegExp = toRegExp(Object.keys(allImportsWithStyle), 'g')
export const transformPlugin = createUnplugin((options: PluginOptions) => {
const { layers, include, exclude, transformStyles } = options
return {
name: `${libraryName}:transform`,
enforce: 'post',
transformInclude (id) {
if (layers.some(layer => id.startsWith(layer))) {
return true
}
if (exclude.some(pattern => id.match(pattern))) {
return false
}
if (include.some(pattern => id.match(pattern))) {
return true
}
},
async transform (code, id) {
const { resolvePath } = createResolver(import.meta.url)
const styles = new Set<string>()
const s = new MagicString(code)
s.replace(componentsRegExp, (full, lazy, name) => {
styles.add(camelize(name))
return full
})
s.replace(importsRegExp, (full, name) => {
styles.add(name)
return full
})
if (styles.size) {
let imports: string = ''
for (const name of styles) {
const style = transformStyles(name)
if (style) {
const path = await resolvePath(style)
imports += genSideEffectsImport(path)
}
}
s.prepend(imports)
}
if (s.hasChanged()) {
return {
code: s.toString(),
map: options.sourcemap
? s.generateMap({ source: id, includeContent: true })
: undefined
}
}
}
}
})