Skip to content

Commit 34fc317

Browse files
committed
feat: add a feature option to support custom component id generator
ref: vitejs/vite-plugin-vue@7a1fc4c
1 parent da26e52 commit 34fc317

File tree

2 files changed

+42
-1
lines changed

2 files changed

+42
-1
lines changed

src/core/index.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,23 @@ export interface Options {
139139
* @default /\.ce\.vue$/
140140
*/
141141
customElement?: boolean | string | RegExp | (string | RegExp)[]
142+
/**
143+
* Customize the component ID generation strategy.
144+
* - `'filepath'`: hash the file path (relative to the project root)
145+
* - `'filepath-source'`: hash the file path and the source code
146+
* - `function`: custom function that takes the file path, source code,
147+
* whether in production mode, and the default hash function as arguments
148+
* - **default:** `'filepath'` in development, `'filepath-source'` in production
149+
*/
150+
componentIdGenerator?:
151+
| 'filepath'
152+
| 'filepath-source'
153+
| ((
154+
filepath: string,
155+
source: string,
156+
isProduction: boolean | undefined,
157+
getHash: (text: string) => string,
158+
) => string)
142159
}
143160
}
144161

src/core/utils/descriptorCache.ts

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,14 @@ const prevCache = new Map<string, SFCDescriptor | undefined>()
2222
export function createDescriptor(
2323
filename: string,
2424
source: string,
25-
{ root, isProduction, sourceMap, compiler, template }: ResolvedOptions,
25+
{
26+
root,
27+
isProduction,
28+
sourceMap,
29+
compiler,
30+
template,
31+
features,
32+
}: ResolvedOptions,
2633
hmr = false,
2734
): SFCParseResult {
2835
const { descriptor, errors } = compiler.parse(source, {
@@ -34,6 +41,23 @@ export function createDescriptor(
3441
// ensure the path is normalized in a way that is consistent inside
3542
// project (relative to root) and on different systems.
3643
const normalizedPath = normalizePath(path.relative(root, filename))
44+
45+
const componentIdGenerator = features?.componentIdGenerator
46+
if (componentIdGenerator === 'filepath') {
47+
descriptor.id = getHash(normalizedPath)
48+
} else if (componentIdGenerator === 'filepath-source') {
49+
descriptor.id = getHash(normalizedPath + source)
50+
} else if (typeof componentIdGenerator === 'function') {
51+
descriptor.id = componentIdGenerator(
52+
normalizedPath,
53+
source,
54+
isProduction,
55+
getHash,
56+
)
57+
} else {
58+
descriptor.id = getHash(normalizedPath + (isProduction ? source : ''))
59+
}
60+
3761
descriptor.id = getHash(normalizedPath + (isProduction ? source : ''))
3862
;(hmr ? hmrCache : cache).set(filename, descriptor)
3963
return { descriptor, errors }

0 commit comments

Comments
 (0)