From 7dcf1151d0eb48ba61cc69200c5de8ba92b0dbbe Mon Sep 17 00:00:00 2001 From: EGOIST <0x142857@gmail.com> Date: Thu, 18 Mar 2021 15:39:27 +0800 Subject: [PATCH] fix: use locally installed @vue/compiler-sfc --- src/index.ts | 25 ++++++++++++++++++++++--- tsup.config.ts | 20 -------------------- 2 files changed, 22 insertions(+), 23 deletions(-) diff --git a/src/index.ts b/src/index.ts index 219bc3d..f53a935 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,5 @@ import path from 'path' import fs from 'fs' -import { parse, compileScript } from '@vue/compiler-sfc' import { Project, SourceFile } from 'ts-morph' import glob from 'fast-glob' @@ -9,7 +8,25 @@ export type Options = { outDir?: string } +let vueCompiler: typeof import('@vue/compiler-sfc') + +const getVueCompiler = () => { + if (!vueCompiler) { + try { + vueCompiler = require(path.resolve('node_modules/@vue/compiler-sfc')) + } catch (error) { + if (error.code === 'MODULE_NOT_FOUND') { + throw new Error(`@vue/compiler-sfc is not founded in ./node_modules`) + } + throw error + } + } + + return vueCompiler +} + export async function build({ input, outDir }: Options) { + const vueCompiler = getVueCompiler() const tsConfigFilePath = fs.existsSync('tsconfig.json') ? 'tsconfig.json' : undefined @@ -30,7 +47,7 @@ export async function build({ input, outDir }: Options) { await Promise.all( files.map(async (file) => { const content = await fs.promises.readFile(file, 'utf8') - const sfc = parse(content) + const sfc = vueCompiler.parse(content) const { script, scriptSetup } = sfc.descriptor if (script || scriptSetup) { let content = '' @@ -40,7 +57,9 @@ export async function build({ input, outDir }: Options) { if (script.lang === 'ts') isTS = true } if (scriptSetup) { - const compiled = compileScript(sfc.descriptor, { id: 'xxx' }) + const compiled = vueCompiler.compileScript(sfc.descriptor, { + id: 'xxx', + }) content += compiled.content if (scriptSetup.lang === 'ts') isTS = true } diff --git a/tsup.config.ts b/tsup.config.ts index f9afd23..ef0e004 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -13,26 +13,6 @@ const options: Options = { }) }, }, - { - // Some modules like `pug` are required in consolidate but should not be bundled - name: 'ignore-require-in-consolidate', - setup(build) { - build.onResolve({ filter: /^[a-z]/ }, (args) => { - if (builtinModules.includes(args.path)) - return { - path: args.path, - external: true, - } - if (args.importer.includes('consolidate')) { - const id = resolve.silent(args.resolveDir, args.path) - if (id) { - return { path: id } - } - return { path: args.path, external: true } - } - }) - }, - }, ], }