From 5f15d9aa4b9024b3764b962bee042d72f94dee91 Mon Sep 17 00:00:00 2001 From: Evan You Date: Tue, 26 May 2020 14:27:01 -0400 Subject: [PATCH] fix(compiler-ssr): should escape template string interpolation chars in generated code --- packages/compiler-core/src/codegen.ts | 2 +- packages/compiler-ssr/__tests__/ssrText.spec.ts | 15 +++++++++++++++ 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/compiler-core/src/codegen.ts b/packages/compiler-core/src/codegen.ts index d7d8b8bfa37..d95b22b6bd7 100644 --- a/packages/compiler-core/src/codegen.ts +++ b/packages/compiler-core/src/codegen.ts @@ -891,7 +891,7 @@ function genTemplateLiteral(node: TemplateLiteral, context: CodegenContext) { for (let i = 0; i < l; i++) { const e = node.elements[i] if (isString(e)) { - push(e.replace(/`/g, '\\`')) + push(e.replace(/(`|\$|\\)/g, '\\$1')) } else { push('${') if (multilines) indent() diff --git a/packages/compiler-ssr/__tests__/ssrText.spec.ts b/packages/compiler-ssr/__tests__/ssrText.spec.ts index 281f518f07f..37c9646d272 100644 --- a/packages/compiler-ssr/__tests__/ssrText.spec.ts +++ b/packages/compiler-ssr/__tests__/ssrText.spec.ts @@ -6,6 +6,21 @@ describe('ssr: text', () => { expect(getCompiledString(`foo`)).toMatchInlineSnapshot(`"\`foo\`"`) }) + test('static text with template string special chars', () => { + expect(getCompiledString(`\`\${foo}\``)).toMatchInlineSnapshot( + `"\`\\\\\`\\\\\${foo}\\\\\`\`"` + ) + }) + + test('static text with char escape', () => { + // the desired generated code should be `\\\$foo` + // snapshot -> inline snapshot goes through two escapes + // so that makes a total of 3 * 2 * 2 = 12 back slashes + expect(getCompiledString(`\\$foo`)).toMatchInlineSnapshot( + `"\`\\\\\\\\\\\\$foo\`"` + ) + }) + test('comments', () => { expect(getCompiledString(``)).toMatchInlineSnapshot( `"\`\`"`