Skip to content

Commit

Permalink
fix: avoid resolving to 2.7 compiler-sfc
Browse files Browse the repository at this point in the history
This can happen in monorepos where Vue 2.7 is in a package's deps
while Vue 3 is only a transitive dep, e.g. from VitePress. Even with
pnpm this can happen because `pnpm run` emulates npm behavior by
injecting NODE_PATH.

ref: vuejs/vitepress#1507
  • Loading branch information
yyx990803 committed Mar 13, 2023
1 parent 40cff6b commit cf36b3e
Showing 1 changed file with 9 additions and 3 deletions.
12 changes: 9 additions & 3 deletions packages/plugin-vue/src/compiler.ts
Expand Up @@ -10,9 +10,7 @@ import type * as _compiler from 'vue/compiler-sfc'

export function resolveCompiler(root: string): typeof _compiler {
// resolve from project root first, then fallback to peer dep (if any)
const compiler =
tryRequire('vue/compiler-sfc', root) || tryRequire('vue/compiler-sfc')

const compiler = tryResolveCompiler(root) || tryResolveCompiler()
if (!compiler) {
throw new Error(
`Failed to resolve vue/compiler-sfc.\n` +
Expand All @@ -24,6 +22,14 @@ export function resolveCompiler(root: string): typeof _compiler {
return compiler
}

function tryResolveCompiler(root?: string) {
const vueMeta = tryRequire('vue/package.json', root)
// make sure to check the version is 3+ since 2.7 now also has vue/compiler-sfc
if (vueMeta && vueMeta.version.split('.')[0] >= 3) {
return tryRequire('vue/compiler-sfc', root)
}
}

const _require = createRequire(import.meta.url)
function tryRequire(id: string, from?: string) {
try {
Expand Down

0 comments on commit cf36b3e

Please sign in to comment.