Skip to content

Commit

Permalink
fix(ssr): fix escape and handling for raw Text, Comment and Static vn…
Browse files Browse the repository at this point in the history
…odes
  • Loading branch information
yyx990803 committed May 1, 2020
1 parent 1bddeea commit 5b09e74
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
31 changes: 30 additions & 1 deletion packages/server-renderer/__tests__/renderToString.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import {
resolveComponent,
ComponentOptions,
ref,
defineComponent
defineComponent,
createTextVNode,
createStaticVNode
} from 'vue'
import { escapeHtml, mockWarn } from '@vue/shared'
import { renderToString, renderComponent } from '../src/renderToString'
Expand Down Expand Up @@ -511,6 +513,33 @@ describe('ssr: renderToString', () => {
})
})

describe('raw vnode types', () => {
test('Text', async () => {
expect(await renderToString(createTextVNode('hello <div>'))).toBe(
`hello &lt;div&gt;`
)
})

test('Comment', async () => {
// https://www.w3.org/TR/html52/syntax.html#comments
expect(
await renderToString(
h('div', [
createCommentVNode('>foo'),
createCommentVNode('->foo'),
createCommentVNode('<!--foo-->'),
createCommentVNode('--!>foo<!-')
])
)
).toBe(`<div><!--foo--><!--foo--><!--foo--><!--foo--></div>`)
})

test('Static', async () => {
const content = `<div id="ok">hello<span>world</span></div>`
expect(await renderToString(createStaticVNode(content))).toBe(content)
})
})

describe('scopeId', () => {
// note: here we are only testing scopeId handling for vdom serialization.
// compiled srr render functions will include scopeId directly in strings.
Expand Down
15 changes: 13 additions & 2 deletions packages/server-renderer/src/renderToString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
createVNode,
Text,
Comment,
Static,
Fragment,
ssrUtils,
Slots,
Expand Down Expand Up @@ -229,6 +230,9 @@ function ssrCompile(
return (compileCache[template] = Function('require', code)(require))
}

// https://www.w3.org/TR/html52/syntax.html#comments
const commentStripRE = /^-?>|<!--|-->|--!>|<!-$/g

function renderVNode(
push: PushFn,
vnode: VNode,
Expand All @@ -237,10 +241,17 @@ function renderVNode(
const { type, shapeFlag, children } = vnode
switch (type) {
case Text:
push(children as string)
push(escapeHtml(children as string))
break
case Comment:
push(children ? `<!--${children}-->` : `<!---->`)
push(
children
? `<!--${(children as string).replace(commentStripRE, '')}-->`
: `<!---->`
)
break
case Static:
push(children as string)
break
case Fragment:
push(`<!--[-->`) // open
Expand Down

0 comments on commit 5b09e74

Please sign in to comment.