This repository has been archived by the owner on Apr 6, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
loader.ts
48 lines (42 loc) · 1.51 KB
/
loader.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
import { createUnplugin } from 'unplugin'
import { parseQuery, parseURL } from 'ufo'
import { Component } from '@nuxt/schema'
import { genImport } from 'knitwork'
interface LoaderOptions {
getComponents(): Component[]
}
export const loaderPlugin = createUnplugin((options: LoaderOptions) => ({
name: 'nuxt-components-loader',
enforce: 'post',
transformInclude (id) {
const { pathname, search } = parseURL(id)
const query = parseQuery(search)
// we only transform render functions
// from `type=template` (in Webpack) and bare `.vue` file (in Vite)
return pathname.endsWith('.vue') && (query.type === 'template' || !search)
},
transform (code) {
return transform(code, options.getComponents())
}
}))
function findComponent (components: Component[], name:string) {
return components.find(({ pascalName, kebabName }) => [pascalName, kebabName].includes(name))
}
function transform (content: string, components: Component[]) {
let num = 0
let imports = ''
const map = new Map<Component, string>()
// replace `_resolveComponent("...")` to direct import
const newContent = content.replace(/ _resolveComponent\("(.*?)"\)/g, (full, name) => {
const component = findComponent(components, name)
if (component) {
const identifier = map.get(component) || `__nuxt_component_${num++}`
map.set(component, identifier)
imports += genImport(component.filePath, identifier)
return ` ${identifier}`
}
// no matched
return full
})
return `${imports}\n${newContent}`
}