niucloud/admin/src/utils/core-component-resolver.ts
wangchen14709853322 5ed9a0ba81 v2.0-beta-20260626
v2框架公测版测试流程请看v2.0-beta.md
2026-07-01 12:25:30 +08:00

58 lines
2.1 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* Core 内动态组件解析pay/diy-link 等),仅 core 使用,不可打进 addon 包
*/
import type { Component } from 'vue'
import { defineAsyncComponent } from 'vue'
export const coreVueModules = {
...import.meta.glob('../app/**/*.vue'),
...import.meta.glob('../components/**/*.vue'),
...import.meta.glob('../layout/**/*.vue')
}
type ViewLoader = () => Promise<{ default: Component }>
function normalizeComponentKey(p: string): string {
return p
.replace(/^@\//, '')
.replace(/^\/src\//, '')
.replace(/^\.\.\//, '')
.replace(/\\/g, '/')
}
function findCoreModuleLoader(componentPath: string): ViewLoader | undefined {
const map = coreVueModules as Record<string, ViewLoader>
if (map[componentPath]) return map[componentPath]
const target = normalizeComponentKey(componentPath)
const key = Object.keys(map).find((k) => normalizeComponentKey(k) === target || normalizeComponentKey(k).endsWith(`/${target}`))
return key ? map[key] : undefined
}
export function resolveAsyncComponent(componentPath: string) {
return defineAsyncComponent(async () => {
const loader = findCoreModuleLoader(componentPath)
if (loader) return (await loader()).default as Component
const mod = await loadCoreVueModule(componentPath)
return mod.default as Component
})
}
// 开发环境glob 直读插件源码(无需 addon-manifest.dev.ts
const allAddonVueModules = import.meta.glob('../addon/**/views/**/*.vue')
export async function loadCoreVueModule(componentPath: string) {
const loader = findCoreModuleLoader(componentPath)
if (loader) return loader()
if (import.meta.env.DEV) {
if (componentPath.includes('/addon/')) {
const m = componentPath.match(/\/addon\/([^/]+)\/views\/(.+)\.vue$/)
if (m) {
const [, addon, rest] = m
const viewLoader = (allAddonVueModules as Record<string, ViewLoader>)[`../addon/${addon}/views/${rest}.vue`]
if (viewLoader) return viewLoader()
}
}
}
throw new Error(`Component not found: ${componentPath}`)
}