Skip to content

Commit

Permalink
fix: compatible vue2
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyinws committed Apr 22, 2024
1 parent 764294c commit 45bb64a
Showing 1 changed file with 34 additions and 6 deletions.
40 changes: 34 additions & 6 deletions src/core/transform/compilers/vue.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,58 @@
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<CompileResult> {
try {
const { code, id } = context
const { parse } = await import('vue/compiler-sfc')

const compileResults = {
script: '',
line: 0,
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
Expand Down

0 comments on commit 45bb64a

Please sign in to comment.