2022-03-16 13:41:37 +00:00
|
|
|
import { pathToFileURL } from 'url'
|
2021-07-28 12:11:32 +00:00
|
|
|
import { createUnplugin } from 'unplugin'
|
|
|
|
import { parseQuery, parseURL } from 'ufo'
|
2021-11-21 16:14:46 +00:00
|
|
|
import { Component } from '@nuxt/schema'
|
2022-02-07 13:45:47 +00:00
|
|
|
import { genImport } from 'knitwork'
|
2022-03-03 10:01:14 +00:00
|
|
|
import MagicString from 'magic-string'
|
2021-07-28 12:11:32 +00:00
|
|
|
|
|
|
|
interface LoaderOptions {
|
|
|
|
getComponents(): Component[]
|
|
|
|
}
|
|
|
|
|
|
|
|
export const loaderPlugin = createUnplugin((options: LoaderOptions) => ({
|
2022-02-10 09:29:49 +00:00
|
|
|
name: 'nuxt:components-loader',
|
2021-07-28 12:11:32 +00:00
|
|
|
enforce: 'post',
|
|
|
|
transformInclude (id) {
|
2022-03-16 13:41:37 +00:00
|
|
|
const { pathname, search } = parseURL(decodeURIComponent(pathToFileURL(id).href))
|
2021-07-28 12:11:32 +00:00
|
|
|
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)
|
|
|
|
},
|
2022-02-28 19:20:41 +00:00
|
|
|
transform (code, id) {
|
|
|
|
return transform(code, id, options.getComponents())
|
2021-07-28 12:11:32 +00:00
|
|
|
}
|
|
|
|
}))
|
|
|
|
|
|
|
|
function findComponent (components: Component[], name:string) {
|
|
|
|
return components.find(({ pascalName, kebabName }) => [pascalName, kebabName].includes(name))
|
|
|
|
}
|
|
|
|
|
2022-02-28 19:20:41 +00:00
|
|
|
function transform (code: string, id: string, components: Component[]) {
|
2021-07-28 12:11:32 +00:00
|
|
|
let num = 0
|
|
|
|
let imports = ''
|
|
|
|
const map = new Map<Component, string>()
|
2022-02-28 19:20:41 +00:00
|
|
|
const s = new MagicString(code)
|
2021-07-28 12:11:32 +00:00
|
|
|
|
|
|
|
// replace `_resolveComponent("...")` to direct import
|
2022-02-28 19:20:41 +00:00
|
|
|
s.replace(/ _resolveComponent\("(.*?)"\)/g, (full, name) => {
|
2021-07-28 12:11:32 +00:00
|
|
|
const component = findComponent(components, name)
|
|
|
|
if (component) {
|
|
|
|
const identifier = map.get(component) || `__nuxt_component_${num++}`
|
|
|
|
map.set(component, identifier)
|
2022-02-17 14:23:55 +00:00
|
|
|
imports += genImport(component.filePath, [{ name: component.export, as: identifier }])
|
2021-07-28 12:11:32 +00:00
|
|
|
return ` ${identifier}`
|
|
|
|
}
|
|
|
|
// no matched
|
|
|
|
return full
|
|
|
|
})
|
|
|
|
|
2022-02-28 19:20:41 +00:00
|
|
|
if (imports) {
|
|
|
|
s.prepend(imports + '\n')
|
|
|
|
}
|
2022-02-10 09:30:34 +00:00
|
|
|
|
2022-03-03 10:01:14 +00:00
|
|
|
if (s.hasChanged()) {
|
|
|
|
return {
|
|
|
|
code: s.toString(),
|
|
|
|
map: s.generateMap({ source: id, includeContent: true })
|
|
|
|
}
|
|
|
|
}
|
2021-07-28 12:11:32 +00:00
|
|
|
}
|