Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 69 additions & 1 deletion packages/nuxt-cli/src/commands/typecheck.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { TSConfig } from 'pkg-types'
import { existsSync, readFileSync } from 'node:fs'
import { writeFile } from 'node:fs/promises'
import { readdir, readFile, realpath, writeFile } from 'node:fs/promises'
import process from 'node:process'

import { styleText } from 'node:util'
Expand Down Expand Up @@ -167,6 +167,10 @@ export default defineCommand({
}
return
}
const vueVersions = await findVueVersions(cwd)
if (vueVersions.length > 1) {
logger.warn(`Multiple versions of ${styleText('cyan', 'vue')} are installed (${vueVersions.join(', ')}). This can break template type augmentations. Dedupe your dependencies or pin a single Vue version before investigating type errors.`)
}

if (hasTTY) {
logger.error(`Type check failed in ${styleText('cyan', duration)}.`)
Expand All @@ -175,6 +179,70 @@ export default defineCommand({
},
})

async function findVueVersions(cwd: string): Promise<string[]> {
const versions = new Set<string>()
const pending: string[] = []
const visited = new Set<string>()

for (let directory = cwd; ; directory = dirname(directory)) {
pending.push(resolve(directory, 'node_modules'))
const parent = dirname(directory)
if (parent === directory) {
break
}
}
pending.reverse()

while (pending.length > 0 && versions.size < 2) {
const nodeModules = pending.pop()!
const resolvedNodeModules = await realpath(nodeModules).catch(() => undefined)
if (!resolvedNodeModules || visited.has(resolvedNodeModules)) {
continue
}
visited.add(resolvedNodeModules)

const resolvedVuePath = await realpath(resolve(resolvedNodeModules, 'vue')).catch(() => undefined)
if (resolvedVuePath) {
try {
const manifest = JSON.parse(await readFile(resolve(resolvedVuePath, 'package.json'), 'utf8')) as { version?: unknown }
if (typeof manifest.version === 'string') {
versions.add(manifest.version)
}
}
catch {
// Ignore incomplete package installations.
}
}

const entries = await readdir(resolvedNodeModules, { withFileTypes: true }).catch(() => [])
for (const entry of entries) {
if (entry.name === '.bin' || entry.name === 'vue') {
continue
}
const packagePath = resolve(resolvedNodeModules, entry.name)
if (entry.name.startsWith('@')) {
const scopedPackages = await readdir(packagePath).catch(() => [])
for (const packageName of scopedPackages) {
pending.push(resolve(packagePath, packageName, 'node_modules'))
}
}
else if (entry.name === '.pnpm') {
const packages = await readdir(packagePath).catch(() => [])
for (const packageName of packages) {
if (packageName.startsWith('vue@')) {
pending.push(resolve(packagePath, packageName, 'node_modules'))
}
}
}
else {
pending.push(resolve(packagePath, 'node_modules'))
}
}
}

return [...versions].sort()
}

const NUXT_PROJECT_REFERENCE_RE = /(?:^|[/\\])tsconfig\.(?:app|server|shared|node)\.json$/

/**
Expand Down
44 changes: 43 additions & 1 deletion packages/nuxt-cli/test/unit/commands/typecheck.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'

import { beforeEach, describe, expect, it, vi } from 'vitest'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

import { runCommand } from '../../../src/run'
import { logger } from '../../../src/utils/logger'
Expand Down Expand Up @@ -31,6 +34,21 @@ function fixture(name: string) {
return fileURLToPath(new URL(`../../fixtures/typecheck/${name}`, import.meta.url))
}

const tempDirs: string[] = []

async function vueProject(...versions: string[]) {
const cwd = await mkdtemp(join(tmpdir(), 'nuxt-typecheck-'))
tempDirs.push(cwd)
for (const [index, version] of versions.entries()) {
const vueDir = index === 0
? join(cwd, 'node_modules/vue')
: join(cwd, `node_modules/dependency-${index}/node_modules/vue`)
await mkdir(vueDir, { recursive: true })
await writeFile(join(vueDir, 'package.json'), JSON.stringify({ name: 'vue', version }))
}
return cwd
}

async function run(cwd: string, ...args: string[]) {
await runCommand('typecheck', ['--cwd', cwd, ...args])
return x.mock.calls[0]?.[1]
Expand All @@ -44,6 +62,10 @@ describe('nuxt typecheck command', () => {
x.mockResolvedValue({ exitCode: 0 })
})

afterEach(async () => {
await Promise.all(tempDirs.splice(0).map(directory => rm(directory, { recursive: true, force: true })))
})

it('should use build mode for Nuxt project references', async () => {
expect(await run(fixture('nuxt-references'))).toEqual(['-b', '--noEmit'])
})
Expand All @@ -67,6 +89,26 @@ describe('nuxt typecheck command', () => {
warn.mockRestore()
})

it('should warn when multiple Vue versions are installed', async () => {
const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {})
x.mockResolvedValueOnce({ exitCode: 2 })

await run(await vueProject('3.5.40', '3.5.41'))

expect(warn).toHaveBeenCalledWith(expect.stringContaining('3.5.40, 3.5.41'))
warn.mockRestore()
})

it('should not warn for duplicate copies of the same Vue version', async () => {
const warn = vi.spyOn(logger, 'warn').mockImplementation(() => {})
x.mockResolvedValueOnce({ exitCode: 2 })

await run(await vueProject('3.5.41', '3.5.41'))

expect(warn).not.toHaveBeenCalled()
warn.mockRestore()
})

it('should not prepare Nuxt when the requested checker is unavailable', async () => {
resolveModulePath.mockReturnValue(undefined)

Expand Down
Loading