ssr-template.spec.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. // @vitest-environment node
  2. import Vue from 'vue'
  3. import {
  4. compileWithWebpack,
  5. createWebpackBundleRenderer
  6. } from './compile-with-webpack'
  7. import { createRenderer } from 'server/index'
  8. import VueSSRClientPlugin from 'server/webpack-plugin/client'
  9. import { RenderOptions } from 'server/create-renderer'
  10. const defaultTemplate = `<html><head></head><body><!--vue-ssr-outlet--></body></html>`
  11. const interpolateTemplate = `<html><head><title>{{ title }}</title></head><body><!--vue-ssr-outlet-->{{{ snippet }}}</body></html>`
  12. async function generateClientManifest(file: string) {
  13. const fs = await compileWithWebpack(file, {
  14. output: {
  15. path: '/',
  16. publicPath: '/',
  17. filename: '[name].js'
  18. },
  19. optimization: {
  20. runtimeChunk: {
  21. name: 'manifest'
  22. }
  23. },
  24. plugins: [new VueSSRClientPlugin()]
  25. })
  26. return JSON.parse(fs.readFileSync('/vue-ssr-client-manifest.json', 'utf-8'))
  27. }
  28. async function createRendererWithManifest(
  29. file: string,
  30. options?: RenderOptions
  31. ) {
  32. const clientManifest = await generateClientManifest(file)
  33. return createWebpackBundleRenderer(
  34. file,
  35. Object.assign(
  36. {
  37. asBundle: true,
  38. template: defaultTemplate,
  39. clientManifest
  40. },
  41. options
  42. )
  43. )
  44. }
  45. describe('SSR: template option', () => {
  46. it('renderToString', async () => {
  47. const renderer = createRenderer({
  48. template: defaultTemplate
  49. })
  50. const context = {
  51. head: '<meta name="viewport" content="width=device-width">',
  52. styles: '<style>h1 { color: red }</style>',
  53. state: { a: 1 }
  54. }
  55. const res = await renderer.renderToString(
  56. new Vue({
  57. template: '<div>hi</div>'
  58. }),
  59. context
  60. )
  61. expect(res).toContain(
  62. `<html><head>${context.head}${context.styles}</head><body>` +
  63. `<div data-server-rendered="true">hi</div>` +
  64. `<script>window.__INITIAL_STATE__={"a":1}</script>` +
  65. `</body></html>`
  66. )
  67. })
  68. it('renderToString with interpolation', async () => {
  69. const renderer = createRenderer({
  70. template: interpolateTemplate
  71. })
  72. const context = {
  73. title: '<script>hacks</script>',
  74. snippet: '<div>foo</div>',
  75. head: '<meta name="viewport" content="width=device-width">',
  76. styles: '<style>h1 { color: red }</style>',
  77. state: { a: 1 }
  78. }
  79. const res = await renderer.renderToString(
  80. new Vue({
  81. template: '<div>hi</div>'
  82. }),
  83. context
  84. )
  85. expect(res).toContain(
  86. `<html><head>` +
  87. // double mustache should be escaped
  88. `<title>&lt;script&gt;hacks&lt;/script&gt;</title>` +
  89. `${context.head}${context.styles}</head><body>` +
  90. `<div data-server-rendered="true">hi</div>` +
  91. `<script>window.__INITIAL_STATE__={"a":1}</script>` +
  92. // triple should be raw
  93. `<div>foo</div>` +
  94. `</body></html>`
  95. )
  96. })
  97. it('renderToString with interpolation and context.rendered', async () => {
  98. const renderer = createRenderer({
  99. template: interpolateTemplate
  100. })
  101. const context = {
  102. title: '<script>hacks</script>',
  103. snippet: '<div>foo</div>',
  104. head: '<meta name="viewport" content="width=device-width">',
  105. styles: '<style>h1 { color: red }</style>',
  106. state: { a: 0 },
  107. rendered: context => {
  108. context.state.a = 1
  109. }
  110. }
  111. const res = await renderer.renderToString(
  112. new Vue({
  113. template: '<div>hi</div>'
  114. }),
  115. context
  116. )
  117. expect(res).toContain(
  118. `<html><head>` +
  119. // double mustache should be escaped
  120. `<title>&lt;script&gt;hacks&lt;/script&gt;</title>` +
  121. `${context.head}${context.styles}</head><body>` +
  122. `<div data-server-rendered="true">hi</div>` +
  123. `<script>window.__INITIAL_STATE__={"a":1}</script>` +
  124. // triple should be raw
  125. `<div>foo</div>` +
  126. `</body></html>`
  127. )
  128. })
  129. it('renderToString w/ template function', async () => {
  130. const renderer = createRenderer({
  131. template: (content, context) =>
  132. `<html><head>${context.head}</head>${content}</html>`
  133. })
  134. const context = {
  135. head: '<meta name="viewport" content="width=device-width">'
  136. }
  137. const res = await renderer.renderToString(
  138. new Vue({
  139. template: '<div>hi</div>'
  140. }),
  141. context
  142. )
  143. expect(res).toContain(
  144. `<html><head>${context.head}</head><div data-server-rendered="true">hi</div></html>`
  145. )
  146. })
  147. it('renderToString w/ template function returning Promise', async () => {
  148. const renderer = createRenderer({
  149. template: (content, context) =>
  150. new Promise<string>(resolve => {
  151. setTimeout(() => {
  152. resolve(`<html><head>${context.head}</head>${content}</html>`)
  153. }, 0)
  154. })
  155. })
  156. const context = {
  157. head: '<meta name="viewport" content="width=device-width">'
  158. }
  159. const res = await renderer.renderToString(
  160. new Vue({
  161. template: '<div>hi</div>'
  162. }),
  163. context
  164. )
  165. expect(res).toContain(
  166. `<html><head>${context.head}</head><div data-server-rendered="true">hi</div></html>`
  167. )
  168. })
  169. it('renderToString w/ template function returning Promise w/ rejection', async () => {
  170. const renderer = createRenderer({
  171. template: () =>
  172. new Promise((resolve, reject) => {
  173. setTimeout(() => {
  174. reject(new Error(`foo`))
  175. }, 0)
  176. })
  177. })
  178. const context = {
  179. head: '<meta name="viewport" content="width=device-width">'
  180. }
  181. try {
  182. await renderer.renderToString(
  183. new Vue({
  184. template: '<div>hi</div>'
  185. }),
  186. context
  187. )
  188. } catch (err: any) {
  189. expect(err.message).toBe(`foo`)
  190. }
  191. })
  192. it('renderToStream', async () => {
  193. const renderer = createRenderer({
  194. template: defaultTemplate
  195. })
  196. const context = {
  197. head: '<meta name="viewport" content="width=device-width">',
  198. styles: '<style>h1 { color: red }</style>',
  199. state: { a: 1 }
  200. }
  201. const res = await new Promise((resolve, reject) => {
  202. const stream = renderer.renderToStream(
  203. new Vue({
  204. template: '<div>hi</div>'
  205. }),
  206. context
  207. )
  208. let res = ''
  209. stream.on('data', chunk => {
  210. res += chunk
  211. })
  212. stream.on('error', reject)
  213. stream.on('end', () => {
  214. resolve(res)
  215. })
  216. })
  217. expect(res).toContain(
  218. `<html><head>${context.head}${context.styles}</head><body>` +
  219. `<div data-server-rendered="true">hi</div>` +
  220. `<script>window.__INITIAL_STATE__={"a":1}</script>` +
  221. `</body></html>`
  222. )
  223. })
  224. it('renderToStream with interpolation', async () => {
  225. const renderer = createRenderer({
  226. template: interpolateTemplate
  227. })
  228. const context = {
  229. title: '<script>hacks</script>',
  230. snippet: '<div>foo</div>',
  231. head: '<meta name="viewport" content="width=device-width">',
  232. styles: '<style>h1 { color: red }</style>',
  233. state: { a: 1 }
  234. }
  235. const res = await new Promise((resolve, reject) => {
  236. const stream = renderer.renderToStream(
  237. new Vue({
  238. template: '<div>hi</div>'
  239. }),
  240. context
  241. )
  242. let res = ''
  243. stream.on('data', chunk => {
  244. res += chunk
  245. })
  246. stream.on('error', reject)
  247. stream.on('end', () => {
  248. resolve(res)
  249. })
  250. })
  251. expect(res).toContain(
  252. `<html><head>` +
  253. // double mustache should be escaped
  254. `<title>&lt;script&gt;hacks&lt;/script&gt;</title>` +
  255. `${context.head}${context.styles}</head><body>` +
  256. `<div data-server-rendered="true">hi</div>` +
  257. `<script>window.__INITIAL_STATE__={"a":1}</script>` +
  258. // triple should be raw
  259. `<div>foo</div>` +
  260. `</body></html>`
  261. )
  262. })
  263. it('renderToStream with interpolation and context.rendered', async () => {
  264. const renderer = createRenderer({
  265. template: interpolateTemplate
  266. })
  267. const context = {
  268. title: '<script>hacks</script>',
  269. snippet: '<div>foo</div>',
  270. head: '<meta name="viewport" content="width=device-width">',
  271. styles: '<style>h1 { color: red }</style>',
  272. state: { a: 0 },
  273. rendered: context => {
  274. context.state.a = 1
  275. }
  276. }
  277. const res = await new Promise((resolve, reject) => {
  278. const stream = renderer.renderToStream(
  279. new Vue({
  280. template: '<div>hi</div>'
  281. }),
  282. context
  283. )
  284. let res = ''
  285. stream.on('data', chunk => {
  286. res += chunk
  287. })
  288. stream.on('error', reject)
  289. stream.on('end', () => {
  290. resolve(res)
  291. })
  292. })
  293. expect(res).toContain(
  294. `<html><head>` +
  295. // double mustache should be escaped
  296. `<title>&lt;script&gt;hacks&lt;/script&gt;</title>` +
  297. `${context.head}${context.styles}</head><body>` +
  298. `<div data-server-rendered="true">hi</div>` +
  299. `<script>window.__INITIAL_STATE__={"a":1}</script>` +
  300. // triple should be raw
  301. `<div>foo</div>` +
  302. `</body></html>`
  303. )
  304. })
  305. it('bundleRenderer + renderToString', async () => {
  306. const renderer = await createWebpackBundleRenderer('app.js', {
  307. asBundle: true,
  308. template: defaultTemplate
  309. })
  310. const context: any = {
  311. head: '<meta name="viewport" content="width=device-width">',
  312. styles: '<style>h1 { color: red }</style>',
  313. state: { a: 1 },
  314. url: '/test'
  315. }
  316. const res = await renderer.renderToString(context)
  317. expect(res).toContain(
  318. `<html><head>${context.head}${context.styles}</head><body>` +
  319. `<div data-server-rendered="true">/test</div>` +
  320. `<script>window.__INITIAL_STATE__={"a":1}</script>` +
  321. `</body></html>`
  322. )
  323. expect(context.msg).toBe('hello')
  324. })
  325. it('bundleRenderer + renderToStream', async () => {
  326. const renderer = await createWebpackBundleRenderer('app.js', {
  327. asBundle: true,
  328. template: defaultTemplate
  329. })
  330. const context: any = {
  331. head: '<meta name="viewport" content="width=device-width">',
  332. styles: '<style>h1 { color: red }</style>',
  333. state: { a: 1 },
  334. url: '/test'
  335. }
  336. const res = await new Promise(resolve => {
  337. const stream = renderer.renderToStream(context)
  338. let res = ''
  339. stream.on('data', chunk => {
  340. res += chunk.toString()
  341. })
  342. stream.on('end', () => {
  343. resolve(res)
  344. })
  345. })
  346. expect(res).toContain(
  347. `<html><head>${context.head}${context.styles}</head><body>` +
  348. `<div data-server-rendered="true">/test</div>` +
  349. `<script>window.__INITIAL_STATE__={"a":1}</script>` +
  350. `</body></html>`
  351. )
  352. expect(context.msg).toBe('hello')
  353. })
  354. const expectedHTMLWithManifest = (options: any = {}) =>
  355. `<html><head>` +
  356. // used chunks should have preload
  357. `<link rel="preload" href="/manifest.js" as="script">` +
  358. `<link rel="preload" href="/main.js" as="script">` +
  359. `<link rel="preload" href="/0.js" as="script">` +
  360. `<link rel="preload" href="/test.css" as="style">` +
  361. // images and fonts are only preloaded when explicitly asked for
  362. (options.preloadOtherAssets
  363. ? `<link rel="preload" href="/test.png" as="image">`
  364. : ``) +
  365. (options.preloadOtherAssets
  366. ? `<link rel="preload" href="/test.woff2" as="font" type="font/woff2" crossorigin>`
  367. : ``) +
  368. // unused chunks should have prefetch
  369. (options.noPrefetch ? `` : `<link rel="prefetch" href="/1.js">`) +
  370. // css assets should be loaded
  371. `<link rel="stylesheet" href="/test.css">` +
  372. `</head><body>` +
  373. `<div data-server-rendered="true"><div>async test.woff2 test.png</div></div>` +
  374. // state should be inlined before scripts
  375. `<script>window.${
  376. options.stateKey || '__INITIAL_STATE__'
  377. }={"a":1}</script>` +
  378. // manifest chunk should be first
  379. `<script src="/manifest.js" defer></script>` +
  380. // async chunks should be before main chunk
  381. `<script src="/0.js" defer></script>` +
  382. `<script src="/main.js" defer></script>` +
  383. `</body></html>`
  384. createClientManifestAssertions(true)
  385. createClientManifestAssertions(false)
  386. function createClientManifestAssertions(runInNewContext) {
  387. it('bundleRenderer + renderToString + clientManifest ()', async () => {
  388. const renderer = await createRendererWithManifest('split.js', {
  389. runInNewContext
  390. })
  391. const res = await renderer.renderToString({ state: { a: 1 } })
  392. expect(res).toContain(expectedHTMLWithManifest())
  393. })
  394. it('bundleRenderer + renderToStream + clientManifest + shouldPreload', async () => {
  395. const renderer = await createRendererWithManifest('split.js', {
  396. runInNewContext,
  397. shouldPreload: (file, type) => {
  398. if (
  399. type === 'image' ||
  400. type === 'script' ||
  401. type === 'font' ||
  402. type === 'style'
  403. ) {
  404. return true
  405. }
  406. }
  407. })
  408. const res = await new Promise(resolve => {
  409. const stream = renderer.renderToStream({ state: { a: 1 } })
  410. let res = ''
  411. stream.on('data', chunk => {
  412. res += chunk.toString()
  413. })
  414. stream.on('end', () => {
  415. resolve(res)
  416. })
  417. })
  418. expect(res).toContain(
  419. expectedHTMLWithManifest({
  420. preloadOtherAssets: true
  421. })
  422. )
  423. })
  424. it('bundleRenderer + renderToStream + clientManifest + shouldPrefetch', async () => {
  425. const renderer = await createRendererWithManifest('split.js', {
  426. runInNewContext,
  427. shouldPrefetch: (file, type) => {
  428. if (type === 'script') {
  429. return false
  430. }
  431. }
  432. })
  433. const res = await new Promise(resolve => {
  434. const stream = renderer.renderToStream({ state: { a: 1 } })
  435. let res = ''
  436. stream.on('data', chunk => {
  437. res += chunk.toString()
  438. })
  439. stream.on('end', () => {
  440. resolve(res)
  441. })
  442. })
  443. expect(res).toContain(
  444. expectedHTMLWithManifest({
  445. noPrefetch: true
  446. })
  447. )
  448. })
  449. it('bundleRenderer + renderToString + clientManifest + inject: false', async () => {
  450. const renderer = await createRendererWithManifest('split.js', {
  451. runInNewContext,
  452. template:
  453. `<html>` +
  454. `<head>{{{ renderResourceHints() }}}{{{ renderStyles() }}}</head>` +
  455. `<body><!--vue-ssr-outlet-->{{{ renderState({ windowKey: '__FOO__', contextKey: 'foo' }) }}}{{{ renderScripts() }}}</body>` +
  456. `</html>`,
  457. inject: false
  458. })
  459. const context = { foo: { a: 1 } }
  460. const res = await renderer.renderToString(context)
  461. expect(res).toContain(
  462. expectedHTMLWithManifest({
  463. stateKey: '__FOO__'
  464. })
  465. )
  466. })
  467. it('bundleRenderer + renderToString + clientManifest + no template', async () => {
  468. const renderer = await createRendererWithManifest('split.js', {
  469. runInNewContext,
  470. template: null as any
  471. })
  472. const context: any = { foo: { a: 1 } }
  473. const res = await renderer.renderToString(context)
  474. const customOutput = `<html><head>${
  475. context.renderResourceHints() + context.renderStyles()
  476. }</head><body>${
  477. res +
  478. context.renderState({
  479. windowKey: '__FOO__',
  480. contextKey: 'foo'
  481. }) +
  482. context.renderScripts()
  483. }</body></html>`
  484. expect(customOutput).toContain(
  485. expectedHTMLWithManifest({
  486. stateKey: '__FOO__'
  487. })
  488. )
  489. })
  490. it('whitespace insensitive interpolation', async () => {
  491. const interpolateTemplate = `<html><head><title>{{title}}</title></head><body><!--vue-ssr-outlet-->{{{snippet}}}</body></html>`
  492. const renderer = createRenderer({
  493. template: interpolateTemplate
  494. })
  495. const context = {
  496. title: '<script>hacks</script>',
  497. snippet: '<div>foo</div>',
  498. head: '<meta name="viewport" content="width=device-width">',
  499. styles: '<style>h1 { color: red }</style>',
  500. state: { a: 1 }
  501. }
  502. const res = await renderer.renderToString(
  503. new Vue({
  504. template: '<div>hi</div>'
  505. }),
  506. context
  507. )
  508. expect(res).toContain(
  509. `<html><head>` +
  510. // double mustache should be escaped
  511. `<title>&lt;script&gt;hacks&lt;/script&gt;</title>` +
  512. `${context.head}${context.styles}</head><body>` +
  513. `<div data-server-rendered="true">hi</div>` +
  514. `<script>window.__INITIAL_STATE__={"a":1}</script>` +
  515. // triple should be raw
  516. `<div>foo</div>` +
  517. `</body></html>`
  518. )
  519. })
  520. it('renderToString + nonce', async () => {
  521. const interpolateTemplate = `<html><head><title>hello</title></head><body><!--vue-ssr-outlet--></body></html>`
  522. const renderer = createRenderer({
  523. template: interpolateTemplate
  524. })
  525. const context = {
  526. state: { a: 1 },
  527. nonce: '4AEemGb0xJptoIGFP3Nd'
  528. }
  529. const res = await renderer.renderToString(
  530. new Vue({
  531. template: '<div>hi</div>'
  532. }),
  533. context
  534. )
  535. expect(res).toContain(
  536. `<html><head>` +
  537. `<title>hello</title>` +
  538. `</head><body>` +
  539. `<div data-server-rendered="true">hi</div>` +
  540. `<script nonce="4AEemGb0xJptoIGFP3Nd">window.__INITIAL_STATE__={"a":1}</script>` +
  541. `</body></html>`
  542. )
  543. })
  544. it('renderToString + custom serializer', async () => {
  545. const expected = `{"foo":123}`
  546. const renderer = createRenderer({
  547. template: defaultTemplate,
  548. serializer: () => expected
  549. })
  550. const context = {
  551. state: { a: 1 }
  552. }
  553. const res = await renderer.renderToString(
  554. new Vue({
  555. template: '<div>hi</div>'
  556. }),
  557. context
  558. )
  559. expect(res).toContain(
  560. `<script>window.__INITIAL_STATE__=${expected}</script>`
  561. )
  562. })
  563. }
  564. })