Skip to content
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

fix: add tests for SSR render #2083

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
13 changes: 13 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import type {
SFCTemplateCompileOptions,
SFCScriptCompileOptions,
} from 'vue/compiler-sfc'

import { selectBlock } from './select'
import { genHotReloadCode } from './hotReload'
import { genCSSModulesCode } from './cssModules'
Expand Down Expand Up @@ -363,6 +364,18 @@ export default function loader(
.join(`\n`) + `\n`
}

if (isServer) {
code += `\nimport { useSSRContext } from 'vue'\n`
code += `const _setup = script.setup\n`
;(code += `script.setup = (props, ctx) => {`),
(code += ` const ssrContext = useSSRContext()`),
(code += ` ;(ssrContext._registeredComponents || (ssrContext._registeredComponents = new Set())).add(${JSON.stringify(
hash(loaderContext.request)
)});`)
code += ` return _setup ? _setup(props, ctx) : undefined`
code += `}\n`
}

// finalize
if (!propsToAttach.length) {
code += `\n\nconst __exports__ = script;`
Expand Down
13 changes: 13 additions & 0 deletions test/fixtures/functional-style.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<script>
import {h} from 'vue';
export default {
functional: true,
render () {
return h('div', { class: 'foo' }, ['functional'])
}
}
</script>

<style>
.foo { color: red; }
</style>
17 changes: 17 additions & 0 deletions test/fixtures/ssr-entry.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { renderToString } from 'vue/server-renderer'
import { createSSRApp } from 'vue'

import Component from '~target'
import * as exports from '~target'

export async function main() {
const instance = createSSRApp(Component)
const ssrContext = {}
const markup = await renderToString(instance, ssrContext)
return {
instance,
markup,
componentModule: Component,
ssrContext,
}
}
25 changes: 25 additions & 0 deletions test/fixtures/ssr-style.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<template>
<div>
<h1>Hello</h1>
<basic/>
<functional-style/>
</div>
</template>

<script>
import Basic from './basic.vue'
import FunctionalStyle from './functional-style.vue'

export default {
components: {
Basic,
FunctionalStyle
}
}
</script>

<style>
h1 { color: green; }
</style>

<style src="./style-import.css"></style>
79 changes: 79 additions & 0 deletions test/ssr.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import { mockServerBundleAndRun, genId, DEFAULT_VUE_USE } from './utils'

test('SSR style and moduleId extraction', async () => {
const { markup, ssrContext } = await mockServerBundleAndRun({
entry: 'ssr-style.vue',
})

expect(markup).toContain('<h1>Hello</h1>')
expect(markup).toContain('Hello from Component A!')
expect(markup).toContain('<div class="foo">functional</div>')
// collect component identifiers during render
expect(Array.from(ssrContext._registeredComponents).length).toBe(3)
})

test('SSR with scoped CSS', async () => {
const { markup } = await mockServerBundleAndRun({
entry: 'scoped-css.vue',
})

const shortId = genId('scoped-css.vue')
const id = `data-v-${shortId}`

expect(markup).toContain(`<div ${id}>`)
expect(markup).toContain(`<svg ${id}>`)
})

test('SSR + CSS Modules', async () => {
const testWithIdent = async (
localIdentName: string | undefined,
regexToMatch: RegExp
) => {
const baseLoaders = [
'style-loader',
{
loader: 'css-loader',
options: {
modules: {
localIdentName,
},
},
},
]

const { componentModule } = await mockServerBundleAndRun({
entry: 'css-modules.vue',
modify: (config: any) => {
config!.module!.rules = [
{
test: /\.vue$/,
use: [DEFAULT_VUE_USE],
},
{
test: /\.css$/,
use: baseLoaders,
},
{
test: /\.stylus$/,
use: [...baseLoaders, 'stylus-loader'],
},
]
},
})

const instance = componentModule.__cssModules

// get local class name
const className = instance!.$style.red
expect(className).toMatch(regexToMatch)
}

// default ident
await testWithIdent(undefined, /^\w{21,}/)

// custom ident
await testWithIdent(
'[path][name]---[local]---[hash:base64:5]',
/css-modules---red---\w{5}/
)
})
76 changes: 76 additions & 0 deletions test/utils.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
/* env jest */
import * as path from 'path'
import * as crypto from 'crypto'
import * as vm from 'vm'
import webpack from 'webpack'
import merge from 'webpack-merge'
// import MiniCssExtractPlugin from 'mini-css-extract-plugin'
import { fs as mfs } from 'memfs'
import { JSDOM, VirtualConsole } from 'jsdom'
import { VueLoaderPlugin } from '..'
import type { VueLoaderOptions } from '..'
import type { Component, App } from 'vue'

function hash(text: string): string {
return crypto.createHash('sha256').update(text).digest('hex').substring(0, 8)
Expand Down Expand Up @@ -168,6 +170,34 @@ export function bundle(
})
}

export function bundleSSR(
options: BundleOptions,
wontThrowError?: boolean
): Promise<{
code: string
stats: webpack.Stats
}> {
if (typeof options.entry === 'string' && /\.vue/.test(options.entry)) {
const vueFile = options.entry
options = merge(options, {
entry: require.resolve('./fixtures/ssr-entry'),
resolve: {
alias: {
'~target': path.resolve(__dirname, './fixtures', vueFile),
},
},
})
}
options = merge(options, {
target: 'node',
output: {
libraryTarget: 'commonjs2',
},
externals: ['vue'],
})
return bundle(options, wontThrowError)
}

export async function mockBundleAndRun(
options: BundleOptions,
wontThrowError?: boolean
Expand Down Expand Up @@ -203,6 +233,52 @@ export async function mockBundleAndRun(
}
}

export async function mockServerBundleAndRun(
options: BundleOptions,
wontThrowError?: boolean
) {
const { code, stats } = await bundleSSR(options, wontThrowError)

const dom = new JSDOM(
`<!DOCTYPE html><html><head></head><body></body></html>`,
{
runScripts: 'outside-only',
virtualConsole: new VirtualConsole(),
}
)

const contextObject = {
module: {} as NodeModule,
require: require,
window: dom.window,
document: dom.window.document,
}
vm.runInNewContext(code, contextObject)

const {
instance,
markup,
componentModule,
ssrContext,
}: {
instance: App<Element>
markup: string
componentModule: Component & {
__cssModules?: { $style: Record<string, string> }
}
ssrContext: { _registeredComponents: Set<string> }
} = await contextObject.module.exports.main()

return {
markup,
componentModule,
instance,
ssrContext,
code,
stats,
}
}

export function normalizeNewline(input: string): string {
return input.replace(new RegExp('\r\n', 'g'), '\n')
}
Expand Down