From 45bb64abc3230389ae363bfa2ad86b9a10a2f6a0 Mon Sep 17 00:00:00 2001 From: yuyinws Date: Mon, 22 Apr 2024 13:21:18 +0800 Subject: [PATCH] fix: compatible vue2 --- src/core/transform/compilers/vue.ts | 40 ++++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 6 deletions(-) diff --git a/src/core/transform/compilers/vue.ts b/src/core/transform/compilers/vue.ts index f9a8361..0eba723 100644 --- a/src/core/transform/compilers/vue.ts +++ b/src/core/transform/compilers/vue.ts @@ -1,10 +1,10 @@ +import type { CompilerError, SFCDescriptor } from 'vue/compiler-sfc' import { PLUGIN_NAME } from '../../constants' import type { CompileResult, Context } from './../../../types' export async function vueCompiler(context: Context): Promise { try { const { code, id } = context - const { parse } = await import('vue/compiler-sfc') const compileResults = { script: '', @@ -12,19 +12,47 @@ export async function vueCompiler(context: Context): Promise { offset: 0, } - const { descriptor, errors } = parse(code, { - filename: id, - }) + let descriptor: SFCDescriptor | undefined + let errors: (CompilerError | SyntaxError)[] = [] + + const Vue = await import('vue') + + if (!Vue || typeof Vue.version !== 'string') { + throw new Error(`[${PLUGIN_NAME}]: Vue is not installed`) + } + else if (Vue.version.startsWith('2.')) { + const { parse } = await import('vue/compiler-sfc') + // @ts-expect-error vue2 compiler-sfc + const _descriptor: any = parse({ + source: code, + filename: id, + }) + + descriptor = _descriptor + errors = _descriptor.errors + } + else if (Vue.version.startsWith('3.')) { + const { parse } = await import('vue/compiler-sfc') + const { descriptor: _descriptor, errors: _errors } = parse(code, { + filename: id, + }) + + descriptor = _descriptor + errors = _errors + } + else { + throw new Error(`[${PLUGIN_NAME}]: Unsupported Vue version: ${Vue.version}`) + } if (errors.length === 0) { - if (descriptor.script) { + if (descriptor?.script) { compileResults.script = descriptor.script.content const { line, offset } = descriptor.script.loc.start compileResults.line = line - 1 compileResults.offset = offset } - else if (descriptor.scriptSetup) { + else if (descriptor?.scriptSetup) { compileResults.script = descriptor.scriptSetup.content const { line, offset } = descriptor.scriptSetup.loc.start compileResults.line = line - 1