Skip to content

Commit 3b6cece

Browse files
committed
feat: new config customComponentResolvers
1 parent 6b34c87 commit 3b6cece

File tree

9 files changed

+42
-9
lines changed

9 files changed

+42
-9
lines changed

example/src/App.vue

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,11 @@
2424
<MarkdownA />
2525
<MarkdownB />
2626
</div>
27+
28+
<div class="block">
29+
<h1>Custom Resolvers (1)</h1>
30+
<MyCustom />
31+
</div>
2732
</template>
2833

2934
<script setup lang='ts'>

example/src/CustomResolved.vue

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
<template>
2+
<h3>Custom Resolved: Hi!</h3>
3+
</template>

example/vite.config.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ const config: UserConfig = {
1919
directoryAsNamespace: true,
2020
globalNamespaces: ['global'],
2121
customLoaderMatcher: ({ path }) => path.endsWith('.md'),
22+
customComponentResolvers: (name) => {
23+
if (name === 'MyCustom')
24+
return '/src/CustomResolved.vue'
25+
},
2226
}),
2327
],
2428
}

src/context.ts

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { relative } from 'path'
22
import Debug from 'debug'
3-
import { ComponentsInfo, ComponentsImportMap, Options } from './types'
3+
import { ComponentsInfo, ComponentsImportMap, Options, ComponentResolver } from './types'
44
import { normalize, toArray, getNameFromFilePath, resolveAlias } from './utils'
55
import { searchComponents } from './fs/glob'
66

@@ -15,12 +15,14 @@ export class Context {
1515
private _componentNameMap: Record<string, ComponentsInfo> = {}
1616
private _imports: ComponentsImportMap = {}
1717
private _importsResolveTasks: Record<string, [(null | Promise<string[]>), (null | ((result: string[]) => void))]> = {}
18+
private _resolvers: ComponentResolver[]
1819

1920
constructor(
2021
public readonly options: Options,
2122
) {
22-
const { extensions, dirs, deep } = options
23+
const { extensions, dirs, deep, customComponentResolvers } = options
2324
const exts = toArray(extensions)
25+
this._resolvers = toArray(customComponentResolvers)
2426

2527
if (!exts.length)
2628
throw new Error('[vite-plugin-components] extensions are required to search for components')
@@ -79,20 +81,29 @@ export class Context {
7981
console.warn(`[vite-plugin-components] component "${name}"(${path}) has naming conflicts with other components, ignored.`)
8082
return
8183
}
82-
this._componentNameMap[name] = { name, path }
84+
this._componentNameMap[name] = { name, path: `/${path}` }
8385
})
8486
}
8587

8688
findComponent(name: string, excludePaths: string[] = []) {
89+
// custom resolvers
90+
for (const resolver of this._resolvers) {
91+
const path = resolver(name)
92+
if (path)
93+
return { name, path }
94+
}
95+
96+
// resolve from fs
8797
const info = this._componentNameMap[name]
88-
if (info && !excludePaths.includes(info.path))
98+
if (info && !excludePaths.includes(info.path) && !excludePaths.includes(info.path.slice(1)))
8999
return info
100+
90101
return undefined
91102
}
92103

93104
findComponents(names: string[], excludePaths: string[] = []) {
94105
return names
95-
.map((name) => this.findComponent(name, excludePaths))
106+
.map(name => this.findComponent(name, excludePaths))
96107
.filter(Boolean) as ComponentsInfo[]
97108
}
98109

src/generator/resolver.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ export async function generateResolver(ctx: Context, reqPath: string) {
3333
debug('using', names, 'imported', components.map(i => i.name))
3434

3535
return `
36-
${components.map(({ name, path }) => `import ${name} from "/${path}"`).join('\n')}
36+
${components.map(({ name, path }) => `import ${name} from "${path}"`).join('\n')}
3737
3838
export default (components) => {
3939
return Object.assign({}, { ${components.map(i => i.name).join(', ')} }, components)

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ const defaultOptions: Options = {
2020
root: process.cwd(),
2121

2222
customLoaderMatcher: () => false,
23+
customComponentResolvers: [],
2324
}
2425

2526
function VitePluginComponents(options: Partial<Options> = {}): Plugin {

src/transforms/customComponent.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ export function CustomComponentTransformer(ctx: Context): Transform {
3939
continue
4040

4141
const var_name = `__vite_component_${id}`
42-
lines.push(`import ${var_name} from "/${component.path}"`)
42+
lines.push(`import ${var_name} from "${component.path}"`)
4343
id += 1
4444

4545
injected.push(`"${name}": ${var_name}`)

src/transforms/vueScriptSetup.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,9 @@ const debug = Debug('vite-plugin-components:transform:script-setup')
88
export function VueScriptSetupTransformer(ctx: Context): Transform {
99
return {
1010
test({ path, query }) {
11-
return path.endsWith('.vue') && query.type === 'script' && (Boolean(query.setup) || query.setup === '')
11+
return path.endsWith('.vue')
12+
&& query.type === 'script'
13+
&& (Boolean(query.setup) || query.setup === '')
1214
},
1315
transform({ code, path, isBuild }) {
1416
const sfcPath = ctx.normalizePath(path)
@@ -23,7 +25,7 @@ export function VueScriptSetupTransformer(ctx: Context): Transform {
2325
const component = ctx.findComponent(normalize(match), [sfcPath])
2426
if (component) {
2527
const var_name = `__vite_component_${id}`
26-
head.push(`import ${var_name} from "/${component.path}"`)
28+
head.push(`import ${var_name} from "${component.path}"`)
2729
id += 1
2830
return var_name
2931
}

src/types.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import { Transform } from 'vite'
22

3+
export type ComponentResolver = (name: string) => string | null | undefined
4+
35
/**
46
* Plugin options.
57
*/
@@ -53,6 +55,11 @@ export interface Options {
5355
* @default ()=>false
5456
*/
5557
customLoaderMatcher: Transform['test']
58+
59+
/**
60+
* Pass a custom function to resolve the component importing path from the component name.
61+
*/
62+
customComponentResolvers: ComponentResolver | ComponentResolver[]
5663
}
5764

5865
export interface ComponentsInfo {

0 commit comments

Comments
 (0)