From d091759f104fdd097aec6ab38591bac50b66280c Mon Sep 17 00:00:00 2001 From: Adam Dilger Date: Fri, 26 Apr 2024 13:53:13 +1000 Subject: [PATCH] (#218) format both script and script setup tags if they exist --- src/preprocessors/vue-preprocessor.ts | 29 ++++-- tests/Vue/__snapshots__/ppsi.spec.js.snap | 103 ++++++++++++++++++++++ tests/Vue/setupAndScript.vue | 45 ++++++++++ 3 files changed, 171 insertions(+), 6 deletions(-) create mode 100644 tests/Vue/setupAndScript.vue diff --git a/src/preprocessors/vue-preprocessor.ts b/src/preprocessors/vue-preprocessor.ts index ddbe2b6..66b2bca 100644 --- a/src/preprocessors/vue-preprocessor.ts +++ b/src/preprocessors/vue-preprocessor.ts @@ -5,14 +5,31 @@ export function vuePreprocessor(code: string, options: PrettierOptions) { const { parse } = require('@vue/compiler-sfc'); const { descriptor } = parse(code); - const content = (descriptor.script ?? descriptor.scriptSetup)?.content; - if (!content) { + const scriptContent = descriptor.script?.content; + const scriptSetupContent = descriptor.scriptSetup?.content; + + if (!scriptContent && !scriptSetupContent) { return code; } - // 'replacer' is a function so it returns the preprocessed code as-is. - // If it were passed as just a string and the string contained special groups (like $&, $`, $', $n, $, etc.) this would produce invalid results - const replacer = () => `\n${preprocessor(content, options)}\n`; + let transformedCode = code; + + const replacer = (content: string) => { + // we pass the second argument as a function to avoid issues with the replacement string + // if string contained special groups (like $&, $`, $', $n, $, etc.) this would produce invalid results + return transformedCode.replace( + content, + () => `\n${preprocessor(content, options)}\n`, + ); + }; + + if (scriptContent) { + transformedCode = replacer(scriptContent); + } + + if (scriptSetupContent) { + transformedCode = replacer(scriptSetupContent); + } - return code.replace(content, replacer); + return transformedCode; } diff --git a/tests/Vue/__snapshots__/ppsi.spec.js.snap b/tests/Vue/__snapshots__/ppsi.spec.js.snap index b4fe3e3..afad6e5 100644 --- a/tests/Vue/__snapshots__/ppsi.spec.js.snap +++ b/tests/Vue/__snapshots__/ppsi.spec.js.snap @@ -57,6 +57,109 @@ function add(a, b) { `; +exports[`setupAndScript.vue - vue-verify: setupAndScript.vue 1`] = ` + + + + + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + + + + + +`; + exports[`sfc.vue - vue-verify: sfc.vue 1`] = ` + + + +