From c568778ea3265d8e57f788b00864c9509bf88a4e Mon Sep 17 00:00:00 2001 From: edison Date: Sat, 21 Oct 2023 12:11:41 +0800 Subject: [PATCH] fix(compiler-sfc): avoid gen useCssVars when targeting SSR (#6979) close #6926 --- .../compiler-sfc/__tests__/cssVars.spec.ts | 68 +++++++++++++++++++ packages/compiler-sfc/src/compileScript.ts | 2 +- .../compiler-sfc/src/script/normalScript.ts | 2 +- 3 files changed, 70 insertions(+), 2 deletions(-) diff --git a/packages/compiler-sfc/__tests__/cssVars.spec.ts b/packages/compiler-sfc/__tests__/cssVars.spec.ts index 5b01d73d772..9fb72d7ad50 100644 --- a/packages/compiler-sfc/__tests__/cssVars.spec.ts +++ b/packages/compiler-sfc/__tests__/cssVars.spec.ts @@ -272,5 +272,73 @@ describe('CSS vars injection', () => { `export default {\n setup(__props, { expose: __expose }) {\n __expose();\n\n_useCssVars(_ctx => ({\n "xxxxxxxx-background": (_unref(background))\n}))` ) }) + + describe('skip codegen in SSR', () => { + test('script setup, inline', () => { + const { content } = compileSFCScript( + `\n` + + ``, + { + inlineTemplate: true, + templateOptions: { + ssr: true + } + } + ) + expect(content).not.toMatch(`_useCssVars`) + }) + + // #6926 + test('script, non-inline', () => { + const { content } = compileSFCScript( + `\n` + + ``, + { + inlineTemplate: false, + templateOptions: { + ssr: true + } + } + ) + expect(content).not.toMatch(`_useCssVars`) + }) + + test('normal script', () => { + const { content } = compileSFCScript( + `\n` + + ``, + { + templateOptions: { + ssr: true + } + } + ) + expect(content).not.toMatch(`_useCssVars`) + }) + }) }) }) diff --git a/packages/compiler-sfc/src/compileScript.ts b/packages/compiler-sfc/src/compileScript.ts index cfcc607c72d..2a33f69936d 100644 --- a/packages/compiler-sfc/src/compileScript.ts +++ b/packages/compiler-sfc/src/compileScript.ts @@ -765,7 +765,7 @@ export function compileScript( if ( sfc.cssVars.length && // no need to do this when targeting SSR - !(options.inlineTemplate && options.templateOptions?.ssr) + !options.templateOptions?.ssr ) { ctx.helperImports.add(CSS_VARS_HELPER) ctx.helperImports.add('unref') diff --git a/packages/compiler-sfc/src/script/normalScript.ts b/packages/compiler-sfc/src/script/normalScript.ts index 76b25c66350..d0f16134273 100644 --- a/packages/compiler-sfc/src/script/normalScript.ts +++ b/packages/compiler-sfc/src/script/normalScript.ts @@ -55,7 +55,7 @@ export function processNormalScript( const s = new MagicString(content) rewriteDefaultAST(scriptAst.body, s, defaultVar) content = s.toString() - if (cssVars.length) { + if (cssVars.length && !ctx.options.templateOptions?.ssr) { content += genNormalScriptCssVarsCode( cssVars, bindings,