Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,12 @@ describe('compiler sfc: transform asset url', () => {
expect(code).toMatch(`"xlink:href": "#myCircle"`)
})

// #9919
test('should transform subpath import paths', () => {
const { code } = compileWithAssetUrls(`<img src="#src/assets/vue.svg" />`)
expect(code).toContain(`_imports_0 from '#src/assets/vue.svg'`)
})

test('should allow for full base URLs, with paths', () => {
const { code } = compileWithAssetUrls(`<img src="./logo.png" />`, {
base: 'http://localhost:3000/src/',
Expand Down
7 changes: 6 additions & 1 deletion packages/compiler-sfc/src/template/templateUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ import { isString } from '@vue/shared'

export function isRelativeUrl(url: string): boolean {
const firstChar = url.charAt(0)
return firstChar === '.' || firstChar === '~' || firstChar === '@'
return (
firstChar === '.' ||
firstChar === '~' ||
firstChar === '@' ||
firstChar === '#'
)
}

const externalRE = /^(https?:)?\/\//
Expand Down
154 changes: 100 additions & 54 deletions packages/compiler-sfc/src/template/transformAssetUrl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,13 +101,19 @@ export const transformAssetUrl: NodeTransform = (

const assetAttrs = (attrs || []).concat(wildCardAttrs || [])
node.props.forEach((attr, index) => {
const isHashFragment =
node.tag === 'use' &&
attr.type === NodeTypes.ATTRIBUTE &&
(attr.name === 'href' || attr.name === 'xlink:href') &&
attr.value?.content[0] === '#'

if (
attr.type !== NodeTypes.ATTRIBUTE ||
!assetAttrs.includes(attr.name) ||
!attr.value ||
isExternalUrl(attr.value.content) ||
isDataUrl(attr.value.content) ||
attr.value.content[0] === '#' ||
isHashFragment ||
(!options.includeAbsolute && !isRelativeUrl(attr.value.content))
) {
return
Expand Down Expand Up @@ -147,70 +153,110 @@ export const transformAssetUrl: NodeTransform = (
}
}

/**
* Resolves or registers an import for the given source path
* @param source - Path to resolve import for
* @param loc - Source location
* @param context - Transform context
* @returns Object containing import name and expression
*/
function resolveOrRegisterImport(
source: string,
loc: SourceLocation,
context: TransformContext,
): {
name: string
exp: SimpleExpressionNode
} {
const existingIndex = context.imports.findIndex(i => i.path === source)
if (existingIndex > -1) {
return {
name: `_imports_${existingIndex}`,
exp: context.imports[existingIndex].exp as SimpleExpressionNode,
}
}

const name = `_imports_${context.imports.length}`
const exp = createSimpleExpression(
name,
false,
loc,
ConstantTypes.CAN_STRINGIFY,
)

// We need to ensure the path is not encoded (to %2F),
// so we decode it back in case it is encoded
context.imports.push({
exp,
path: decodeURIComponent(source),
})

return { name, exp }
}
Comment on lines +163 to +195
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Dedupe mismatch when paths differ only by encoding; also guard decode errors

findIndex(i => i.path === source) compares encoded input against a decoded value you push (decodeURIComponent(source)), so 'foo%20bar.svg' and 'foo bar.svg' won’t dedupe. Also, decodeURIComponent can throw on malformed encodings.

Refactor to normalize once, use it for lookup and push, and catch decode errors.

Apply this diff:

-  const existingIndex = context.imports.findIndex(i => i.path === source)
+  // Normalize once for stable matching (handles 'foo%20bar.svg' vs 'foo bar.svg')
+  let normalized = source
+  try {
+    normalized = decodeURIComponent(source)
+  } catch {
+    // keep original if not valid percent-encoding
+  }
+  const existingIndex = context.imports.findIndex(i => i.path === normalized)
@@
-  context.imports.push({
-    exp,
-    path: decodeURIComponent(source),
-  })
+  context.imports.push({
+    exp,
+    path: normalized,
+  })
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
function resolveOrRegisterImport(
source: string,
loc: SourceLocation,
context: TransformContext,
): {
name: string
exp: SimpleExpressionNode
} {
const existingIndex = context.imports.findIndex(i => i.path === source)
if (existingIndex > -1) {
return {
name: `_imports_${existingIndex}`,
exp: context.imports[existingIndex].exp as SimpleExpressionNode,
}
}
const name = `_imports_${context.imports.length}`
const exp = createSimpleExpression(
name,
false,
loc,
ConstantTypes.CAN_STRINGIFY,
)
// We need to ensure the path is not encoded (to %2F),
// so we decode it back in case it is encoded
context.imports.push({
exp,
path: decodeURIComponent(source),
})
return { name, exp }
}
function resolveOrRegisterImport(
source: string,
loc: SourceLocation,
context: TransformContext,
): {
name: string
exp: SimpleExpressionNode
} {
// Normalize once for stable matching (handles 'foo%20bar.svg' vs 'foo bar.svg')
let normalized = source
try {
normalized = decodeURIComponent(source)
} catch {
// keep original if not valid percent-encoding
}
const existingIndex = context.imports.findIndex(i => i.path === normalized)
if (existingIndex > -1) {
return {
name: `_imports_${existingIndex}`,
exp: context.imports[existingIndex].exp as SimpleExpressionNode,
}
}
const name = `_imports_${context.imports.length}`
const exp = createSimpleExpression(
name,
false,
loc,
ConstantTypes.CAN_STRINGIFY,
)
context.imports.push({
exp,
path: normalized,
})
return { name, exp }
}
🤖 Prompt for AI Agents
In packages/compiler-sfc/src/template/transformAssetUrl.ts around lines 163 to
195, the import dedupe logic currently compares the raw source against a decoded
path and calls decodeURIComponent without handling errors; normalize the source
once into a safePath variable by attempting decodeURIComponent(source) inside a
try/catch (on decode error, fall back to the original source), use safePath for
both the findIndex lookup and for the path stored on the pushed import, and keep
the created exp/name logic unchanged so the same normalized path dedupes
correctly even when inputs differ only by encoding.


/**
* Transforms asset URLs into import expressions or string literals
*/
function getImportsExpressionExp(
path: string | null,
hash: string | null,
loc: SourceLocation,
context: TransformContext,
): ExpressionNode {
if (path) {
let name: string
let exp: SimpleExpressionNode
const existingIndex = context.imports.findIndex(i => i.path === path)
if (existingIndex > -1) {
name = `_imports_${existingIndex}`
exp = context.imports[existingIndex].exp as SimpleExpressionNode
} else {
name = `_imports_${context.imports.length}`
exp = createSimpleExpression(
name,
false,
loc,
ConstantTypes.CAN_STRINGIFY,
)

// We need to ensure the path is not encoded (to %2F),
// so we decode it back in case it is encoded
context.imports.push({
exp,
path: decodeURIComponent(path),
})
}
// Neither path nor hash - return empty string
if (!path && !hash) {
return createSimpleExpression(`''`, false, loc, ConstantTypes.CAN_STRINGIFY)
}

if (!hash) {
return exp
}
// Only hash without path - treat hash as the import source (likely a subpath import)
if (!path && hash) {
const { exp } = resolveOrRegisterImport(hash, loc, context)
return exp
}

// Only path without hash - straightforward import
if (path && !hash) {
const { exp } = resolveOrRegisterImport(path, loc, context)
return exp
}

// At this point, we know we have both path and hash components
const { name } = resolveOrRegisterImport(path!, loc, context)

// Combine path import with hash
const hashExp = `${name} + '${hash}'`
const finalExp = createSimpleExpression(
hashExp,
false,
loc,
ConstantTypes.CAN_STRINGIFY,
)

// No hoisting needed
if (!context.hoistStatic) {
return finalExp
}

const hashExp = `${name} + '${hash}'`
const finalExp = createSimpleExpression(
hashExp,
// Check for existing hoisted expression
const existingHoistIndex = context.hoists.findIndex(h => {
return (
h &&
h.type === NodeTypes.SIMPLE_EXPRESSION &&
!h.isStatic &&
h.content === hashExp
)
})

// Return existing hoisted expression if found
if (existingHoistIndex > -1) {
return createSimpleExpression(
`_hoisted_${existingHoistIndex + 1}`,
false,
loc,
ConstantTypes.CAN_STRINGIFY,
)

if (!context.hoistStatic) {
return finalExp
}

const existingHoistIndex = context.hoists.findIndex(h => {
return (
h &&
h.type === NodeTypes.SIMPLE_EXPRESSION &&
!h.isStatic &&
h.content === hashExp
)
})
if (existingHoistIndex > -1) {
return createSimpleExpression(
`_hoisted_${existingHoistIndex + 1}`,
false,
loc,
ConstantTypes.CAN_STRINGIFY,
)
}
return context.hoist(finalExp)
} else {
return createSimpleExpression(`''`, false, loc, ConstantTypes.CAN_STRINGIFY)
}

// Hoist the expression and return the hoisted expression
return context.hoist(finalExp)
}
Loading