# Why Cursor imports files that do not exist

- Tool: Cursor
- Difficulty: Beginner
- Time required: 10-15 min
- Compatibility: Cursor Free+, TypeScript/JavaScript projects
- Last updated: March 2026

## TL;DR

Cursor frequently imports modules, functions, and types that do not exist in your project because it hallucinates based on common naming patterns. By referencing your package.json with @file, adding import validation rules to .cursorrules, and running TypeScript compilation checks after generation, you catch and fix phantom imports before they cause runtime errors.

## Fixing phantom imports in Cursor-generated code

Cursor's AI models predict likely import paths based on naming patterns, not your actual file system. This causes imports of non-existent files, wrong package names, and incorrect relative paths. This tutorial teaches prevention, detection, and fixing strategies.

## Before you start

- Cursor installed with a TypeScript or JavaScript project
- TypeScript compiler configured (tsconfig.json)
- package.json with your project dependencies
- Familiarity with Cursor Chat (Cmd+L) and Cmd+K

## Step-by-step guide

### 1. Add import validation rules to .cursor/rules

Create rules that guide Cursor to use only verified import paths. Reference your project structure and installed packages.

```
---
description: Import validation rules
globs: "src/**/*.ts,src/**/*.tsx"
alwaysApply: true
---

## Import Rules
- ONLY import from packages listed in package.json
- ONLY import from files that exist in the project
- Use @/ alias for src/ imports (configured in tsconfig)
- NEVER guess at import paths — ask if unsure
- NEVER import from packages not in package.json
- Check @package.json before using any third-party import

## Known Project Structure
- @/components/ — React components
- @/hooks/ — custom hooks
- @/lib/ — utility functions
- @/types/ — TypeScript types
- @/services/ — API service classes
- @/config/ — configuration modules

## Common False Imports to AVOID
- Do NOT import from '@/utils' (use @/lib instead)
- Do NOT import from 'lodash' (not installed, use native)
- Do NOT import from '@/api' (use @/services instead)
```

**Expected result:** Cursor uses verified import paths and avoids hallucinating non-existent modules.

### 2. Reference package.json and tsconfig in prompts

Include @package.json when asking Cursor to generate code that needs external imports. This gives the AI visibility into what packages are actually installed.

```
// Cursor Chat prompt (Cmd+L):
// @package.json @tsconfig.json
// Generate a date formatting utility at src/lib/dates.ts.
// Only use packages that are in our package.json.
// If a package is needed but not installed, tell me
// instead of importing it.

// This prevents Cursor from importing moment, luxon, or
// other date libraries that are not in your dependencies.
```

> Pro tip: Adding 'If a package is needed but not installed, tell me instead of importing it' forces Cursor to flag missing dependencies rather than silently importing them.

**Expected result:** Cursor only imports from installed packages and flags missing dependencies.

### 3. Run TypeScript compiler to catch phantom imports

After Cursor generates code, run the TypeScript compiler in no-emit mode to catch any import errors. This is the fastest way to find non-existent imports.

```
// Terminal:
npx tsc --noEmit

// Common errors from phantom imports:
// Cannot find module '@/utils/helpers' or its corresponding type declarations
// Module '@/api/userClient' has no exported member 'fetchUser'
// Cannot find module 'lodash/debounce'

// Paste errors into Cursor Chat:
// @package.json These import errors appeared after your
// last generation. Fix them using only packages in our
// package.json and files that exist in our project.
```

**Expected result:** TypeScript compiler catches all phantom imports so you can fix them before runtime.

### 4. Fix phantom imports with Cursor

Paste the TypeScript errors back into Cursor Chat and ask it to fix the imports. Reference the files that DO exist so Cursor can find the correct paths.

```
// Cursor Chat prompt (Cmd+L):
// @src/lib/ @package.json
// Fix these import errors:
// 1. '@/utils/helpers' does not exist → find the correct
//    path in src/lib/ that has the needed function
// 2. 'lodash/debounce' is not installed → implement a
//    simple debounce function in src/lib/debounce.ts
// 3. '@/api/userClient' does not exist → use the existing
//    @/services/UserService instead
```

**Expected result:** All phantom imports replaced with correct paths to existing files and packages.

### 5. Prevent phantom imports in Composer sessions

When using Composer Agent mode, which creates multiple files, add extra context upfront to prevent phantom imports across the generated files.

```
// Composer prompt (Cmd+I):
// @package.json @src/lib/ @src/services/ @src/types/
// Generate a new notification module with:
// - src/services/NotificationService.ts
// - src/hooks/useNotifications.ts
// - src/types/notification.ts
//
// IMPORTANT: Only import from:
// - Packages in package.json
// - Files that already exist (referenced above)
// - Files you are creating in this session
// Do NOT import from any path that does not exist.
```

**Expected result:** Multiple generated files with only valid imports to existing code and packages.

## Complete code example

File: `.cursor/rules/imports.mdc`

```markdown
---
description: Import validation and path rules
globs: "src/**/*.{ts,tsx}"
alwaysApply: true
---

## Valid Import Sources
1. Installed packages (listed in package.json dependencies)
2. Existing project files (verified by file system)
3. Files being created in the current generation

## Project Path Aliases
- @/ → src/ (configured in tsconfig.json paths)
- Use @/ for all internal imports
- NEVER use relative paths that go up more than 2 levels (../../..)

## Project Directory Map
```
src/
  components/    → React components (*.tsx)
  hooks/         → Custom hooks (use*.ts)
  lib/           → Utility functions
  services/      → API and business logic classes
  types/         → TypeScript interfaces and types
  config/        → Configuration modules
  middleware/    → Express/API middleware
```

## Import Validation Rules
- Check @package.json before importing any npm package
- If a package is needed but not installed, TELL the user
- NEVER silently import non-existent packages
- NEVER guess at file paths — reference @src/ to see what exists
- Use 'import type' for type-only imports

## Commonly Hallucinated Imports (DO NOT USE)
- '@/utils/*' → use '@/lib/*' instead
- '@/api/*' → use '@/services/*' instead  
- '@/store/*' → use '@/hooks/*' or '@/contexts/*'
- 'lodash' → not installed, use native JS
- 'moment' → not installed, use date-fns or native Date
```

## Common mistakes

- **Cursor importing from '@/utils' when the directory is called '@/lib'** — Cursor hallucinate common directory names from its training data. If your project uses 'lib' instead of 'utils', Cursor may not know. Fix: Add your actual directory names to .cursorrules under 'Project Directory Map'. List common aliases to avoid.
- **Cursor importing packages not in package.json** — Cursor knows popular packages (lodash, moment, axios) and imports them assuming they are installed. Fix: Reference @package.json in every prompt. Add 'ONLY import packages in package.json' to your rules.
- **Not running TypeScript compiler after generation** — Phantom imports do not cause errors until runtime or type-checking. Casual review may miss them. Fix: Run npx tsc --noEmit after every Cursor generation session. Add it to your pre-commit hook.

## Best practices

- Reference @package.json when generating code that needs external imports
- Add your project directory map to .cursorrules so Cursor knows actual paths
- Run npx tsc --noEmit after every Cursor generation session
- List commonly hallucinated imports in .cursorrules with correct alternatives
- Use 'tell me if a package is needed but not installed' in prompts
- Reference @src/ folders when using Composer to generate multiple files
- Add TypeScript compilation to your pre-commit hook to catch phantom imports

## Frequently asked questions

### Why does Cursor import files that do not exist?

Cursor predicts import paths based on naming patterns, not your file system. If common patterns (utils, api, store) differ from your structure (lib, services, contexts), Cursor will hallucinate the common names.

### Can Cursor check if imports are valid?

Not automatically during generation. Use Ask mode to verify: '@codebase Check if all imports in this file resolve to existing modules.' Or run npx tsc --noEmit for definitive validation.

### How do I handle imports from packages I plan to install?

Install the package first (npm install), then generate code. Or tell Cursor: 'I will install axios. Generate code using axios with proper imports.' Then install before compiling.

### Will .cursorrules prevent all phantom imports?

Rules significantly reduce them but cannot eliminate them entirely, especially in long sessions. Always run TypeScript compilation as a safety net.

### Can I make Cursor aware of my full file tree?

Yes. Use @folder to reference entire directories, giving Cursor visibility into what exists. For large projects, use .cursorignore to exclude irrelevant directories and keep indexing focused.

---

Source: https://www.rapidevelopers.com/cursor-tutorial/how-to-handle-incomplete-code-references-when-cursor-ai-tries-to-import-non-existent-modules
© RapidDev — https://www.rapidevelopers.com/cursor-tutorial/how-to-handle-incomplete-code-references-when-cursor-ai-tries-to-import-non-existent-modules
