Skip to content

fix: skip quote replacement in interpolation #28

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 16, 2025
Merged
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
18 changes: 18 additions & 0 deletions src/utils/template.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,10 @@ export async function transpileVueTemplate(
for (const item of expressions) {
item.replacement = transformMap.get(item) ?? item.src

if (!shouldReplaceQuote(item)) {
continue
}

// the source should only have one of the quotes
const sourceQuote = getSourceQuote(
content,
Expand Down Expand Up @@ -212,6 +216,20 @@ export function replaceQuote(code: string, target: string, replace: string): str
return res
}

function shouldReplaceQuote(expression: Expression): boolean {
if (!expression.src.includes(`'`) && !expression.src.includes(`"`)) {
return false
}

// skip the expression in the interpolation, it doesn't care about the quote
const secondLastTrack = expression.track.at(-2)
if (secondLastTrack?.type === NodeTypes.INTERPOLATION) {
return false
}

return true
}

function getSourceQuote(code: string, start: number, end: number): string | null {
const source = code.slice(start, end)
const quotes = ['"', '\'']
Expand Down
26 changes: 26 additions & 0 deletions test/template.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,32 @@ describe('transform typescript template', () => {
expect(output).toBe(`'test'`)
})

it('handles quotes in interpolations', async () => {
expect(
await fixture(`
<template>
<div>
<div :class="$test('foobar', \`Foobar 'test'\`)" />
<div>{{ $test('foobar', "Foobar 'test'") }}</div>
<div>{{ $test('foobar', 'Foobar test') }}</div>
<div>{{ $test('foobar', \`Foobar ' " ''" test\`) }}</div>
</div>
</template>
`),
).toMatchInlineSnapshot(`
"
<template>
<div>
<div :class="$test('foobar', \`Foobar \\'test\\'\`)" />
<div>{{ $test("foobar", "Foobar 'test'") }}</div>
<div>{{ $test("foobar", "Foobar test") }}</div>
<div>{{ $test("foobar", \`Foobar ' " ''" test\`) }}</div>
</div>
</template>
"
`)
})

async function fixture(src: string) {
const requireFromVue = createRequire(resolveModulePath('vue'))
const { parse } = requireFromVue('@vue/compiler-dom') as typeof import('@vue/compiler-dom')
Expand Down