Skip to content

Commit

Permalink
feat: add a feature option to support custom component id generator
Browse files Browse the repository at this point in the history
  • Loading branch information
sxzz committed Nov 26, 2024
1 parent f7499e7 commit 8b6a8c2
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
17 changes: 17 additions & 0 deletions src/core/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,23 @@ export interface Options {
* @default /\.ce\.vue$/
*/
customElement?: boolean | string | RegExp | (string | RegExp)[]
/**
* Customize the component ID generation strategy.
* - `'filepath'`: hash the file path (relative to the project root)
* - `'filepath-source'`: hash the file path and the source code
* - `function`: custom function that takes the file path, source code,
* whether in production mode, and the default hash function as arguments
* - **default:** `'filepath'` in development, `'filepath-source'` in production
*/
componentIdGenerator?:
| 'filepath'
| 'filepath-source'
| ((
filepath: string,
source: string,
isProduction: boolean | undefined,
getHash: (text: string) => string,
) => string)
}
}

Expand Down
26 changes: 25 additions & 1 deletion src/core/utils/descriptorCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,14 @@ const prevCache = new Map<string, SFCDescriptor | undefined>()
export function createDescriptor(
filename: string,
source: string,
{ root, isProduction, sourceMap, compiler, template }: ResolvedOptions,
{
root,
isProduction,
sourceMap,
compiler,
template,
features,
}: ResolvedOptions,
hmr = false,
): SFCParseResult {
const { descriptor, errors } = compiler.parse(source, {
Expand All @@ -34,6 +41,23 @@ export function createDescriptor(
// ensure the path is normalized in a way that is consistent inside
// project (relative to root) and on different systems.
const normalizedPath = normalizePath(path.relative(root, filename))

const componentIdGenerator = features?.componentIdGenerator
if (componentIdGenerator === 'filepath') {
descriptor.id = getHash(normalizedPath)
} else if (componentIdGenerator === 'filepath-source') {
descriptor.id = getHash(normalizedPath + source)
} else if (typeof componentIdGenerator === 'function') {
descriptor.id = componentIdGenerator(
normalizedPath,
source,
isProduction,
getHash,
)
} else {
descriptor.id = getHash(normalizedPath + (isProduction ? source : ''))
}

descriptor.id = getHash(normalizedPath + (isProduction ? source : ''))
;(hmr ? hmrCache : cache).set(filename, descriptor)
return { descriptor, errors }
Expand Down

0 comments on commit 8b6a8c2

Please sign in to comment.