fix(ssr/sfc-css-vars): fix v-bind css vars codegen for SSR

fix #5443
close #5444
This commit is contained in:
Evan You 2022-05-17 09:21:36 +08:00
parent 2a9e9a4096
commit efea4a8b57
5 changed files with 31 additions and 26 deletions

View File

@ -1039,8 +1039,7 @@ return (_ctx, _cache) => {
`;
exports[`SFC compile <script setup> inlineTemplate mode ssr codegen 1`] = `
"import { useCssVars as _useCssVars, unref as _unref } from 'vue'
import { ssrRenderAttrs as _ssrRenderAttrs, ssrInterpolate as _ssrInterpolate } from \\"vue/server-renderer\\"
"import { ssrRenderAttrs as _ssrRenderAttrs, ssrInterpolate as _ssrInterpolate } from \\"vue/server-renderer\\"
import { ref } from 'vue'
@ -1048,15 +1047,11 @@ export default {
__ssrInlineRender: true,
setup(__props) {
_useCssVars(_ctx => ({
\\"xxxxxxxx-count\\": (count.value)
}))
const count = ref(0)
return (_ctx, _push, _parent, _attrs) => {
const _cssVars = { style: {
\\"xxxxxxxx-count\\": (count.value)
\\"--xxxxxxxx-count\\": (count.value)
}}
_push(\`<!--[--><div\${
_ssrRenderAttrs(_cssVars)

View File

@ -1,5 +1,5 @@
import { BindingTypes } from '@vue/compiler-core'
import { compileSFCScript as compile, assertCode } from './utils'
import { compileSFCScript as compile, assertCode, mockId } from './utils'
describe('SFC compile <script setup>', () => {
test('should expose top level declarations', () => {
@ -726,6 +726,8 @@ defineExpose({ foo: 123 })
expect(content).toMatch(`\n __ssrInlineRender: true,\n`)
expect(content).toMatch(`return (_ctx, _push`)
expect(content).toMatch(`ssrInterpolate`)
expect(content).not.toMatch(`useCssVars`)
expect(content).toMatch(`"--${mockId}-count": (count.value)`)
assertCode(content)
})
})

View File

@ -432,7 +432,8 @@ export function compileScript(
)
}
const propKey = prop.key.type === 'StringLiteral'
const propKey =
prop.key.type === 'StringLiteral'
? prop.key.value
: (prop.key as Identifier).name
@ -1304,7 +1305,11 @@ export function compileScript(
}
// 8. inject `useCssVars` calls
if (cssVars.length) {
if (
cssVars.length &&
// no need to do this when targeting SSR
!(options.inlineTemplate && options.templateOptions?.ssr)
) {
helperImports.add(CSS_VARS_HELPER)
helperImports.add('unref')
s.prependRight(

View File

@ -202,7 +202,7 @@ function doCompileTemplate({
cacheHandlers: true,
ssrCssVars:
ssr && ssrCssVars && ssrCssVars.length
? genCssVarsFromList(ssrCssVars, shortId, isProd)
? genCssVarsFromList(ssrCssVars, shortId, isProd, true)
: '',
scopeId: scoped ? longId : undefined,
slotted,

View File

@ -18,10 +18,13 @@ const cssVarRE = /v-bind\s*\(((?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*)\)/g
export function genCssVarsFromList(
vars: string[],
id: string,
isProd: boolean
isProd: boolean,
isSSR = false
): string {
return `{\n ${vars
.map(key => `"${genVarName(id, key, isProd)}": (${key})`)
.map(
key => `"${isSSR ? `--` : ``}${genVarName(id, key, isProd)}": (${key})`
)
.join(',\n ')}\n}`
}