Skip to content

Commit ecd53f0

Browse files
authored
fix: isPackageExists checks for the package incorrectly, close #125 (#126)
1 parent d94525d commit ecd53f0

File tree

2 files changed

+26
-6
lines changed

2 files changed

+26
-6
lines changed

vite-plugin-mock-dev-server/src/compiler/compile.ts

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,14 @@
11
import type { CompilerOptions, CompilerResult, MockRawData, TransformResult } from './types'
22
import process from 'node:process'
3-
import { isPackageExists } from 'local-pkg'
3+
import { isPackageExists } from '../utils'
44
import { transformWithEsbuild } from './esbuild'
55
import { loadFromCode } from './loadFromCode'
66
import { transformWithRolldown } from './rolldown'
77

8-
const hasRolldown = isPackageExists('rolldown')
9-
const hasEsbuild = isPackageExists('esbuild')
10-
118
export async function transform(entryPoint: string, options: CompilerOptions): Promise<TransformResult> {
12-
if (hasRolldown)
9+
if (await isPackageExists('rolldown'))
1310
return transformWithRolldown(entryPoint, options)
14-
if (hasEsbuild)
11+
if (await isPackageExists('esbuild'))
1512
return transformWithEsbuild(entryPoint, options)
1613
throw new Error('rolldown or esbuild not found')
1714
}

vite-plugin-mock-dev-server/src/utils/is.ts

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { Readable, Stream } from 'node:stream'
2+
import { hasOwn } from '@pengzhanbo/utils'
23

34
export function isStream(stream: unknown): stream is Stream {
45
return stream !== null
@@ -12,3 +13,25 @@ export function isReadableStream(stream: unknown): stream is Readable {
1213
&& typeof (stream as any)._read === 'function'
1314
&& typeof (stream as any)._readableState === 'object'
1415
}
16+
17+
const PACKAGE_CACHE: Record<string, boolean> = {}
18+
19+
export async function isPackageExists(mod: string): Promise<boolean> {
20+
if (hasOwn(PACKAGE_CACHE, mod)) {
21+
return PACKAGE_CACHE[mod]
22+
}
23+
try {
24+
// @ts-expect-error fallback for node
25+
if (import.meta.resolve) {
26+
PACKAGE_CACHE[mod] = !!import.meta.resolve(mod)
27+
}
28+
else {
29+
await import(mod)
30+
PACKAGE_CACHE[mod] = true
31+
}
32+
return PACKAGE_CACHE[mod]
33+
}
34+
catch {}
35+
PACKAGE_CACHE[mod] = false
36+
return false
37+
}

0 commit comments

Comments
 (0)