Vite+React项目报错Cannot find the name 'document'求助
问题:Vite+React+TypeScript项目出现「Cannot find the name 'document'」错误
运行项目时收到错误提示:
Cannot find the name 'document'. Do you need to change your target library? Try changing the compiler option 'lib' to include 'dom'.ts
项目入口代码:
import React from 'react' import ReactDOM from 'react-dom/client' import { BrowserRouter as Router, Routes, Route } from 'react-router-dom' import Login from '../src/pages/login' import Forms from '../src/pages/forms' import '../src/styles/global.css' ReactDOM.createRoot(document.getElementById('root')!).render( <React.StrictMode> <Router> <Routes> <Route path="/login" element={<Login />} /> <Route path="/forms" element={<Forms />} /> </Routes> </Router> </React.StrictMode>, )
已配置tsconfig.json,其中compilerOptions.lib已包含DOM相关项:
{ "compilerOptions": { "target": "ES2020", "useDefineForClassFields": true, "lib": ["ES2020", "DOM", "DOM.Iterable"], "module": "ESNext", "skipLibCheck": true, /* Bundler mode */ "moduleResolution": "bundler", "allowImportingTsExtensions": true, "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", /* Linting */ "strict": true, "noUnusedLocals": true, "noUnusedParameters": true, "noFallthroughCasesInSwitch": true }, "include": ["src"], "references": [{ "path": "./tsconfig.node.json" }] }
原因分析与解决方法
可能原因
- 入口文件不在
src目录下:从代码里的../src/pages/login路径来看,你的入口文件(比如main.tsx)大概率在src目录外面。而tsconfig.json的include只配置了["src"],外部文件不会应用DOM相关的lib配置,TypeScript会默认用无DOM的环境检查。 tsconfig.node.json的配置冲突:项目引用了这个文件,它是针对Node.js环境的配置(默认没有DOM lib),如果你的入口文件被这个配置覆盖处理,也会触发错误。- IDE缓存未更新:VSCode等编辑器可能缓存了旧的TypeScript配置,没有加载最新的
tsconfig.json。
解决步骤
- 调整文件位置与路径:把入口文件移到
src目录下,同时修正import路径为相对src的写法,比如import Login from './pages/login',这样文件会被tsconfig.json的规则覆盖。如果不想移动文件,就修改tsconfig.json的include,把入口文件名加进去:"include": ["src", "main.tsx"](替换成你的入口文件名)。 - 检查
tsconfig.node.json配置:打开这个文件,确保它的include只包含Node相关的文件(比如vite.config.ts),不要包含React业务文件。示例配置如下:{ "compilerOptions": { "composite": true, "skipLibCheck": true, "module": "ESNext", "moduleResolution": "bundler", "allowSyntheticDefaultImports": true }, "include": ["vite.config.ts"] } - 重启TypeScript服务:在VSCode里按
Ctrl+Shift+P(Windows)或Cmd+Shift+P(Mac),输入TypeScript: Restart TS Server,刷新编辑器缓存,让新配置生效。
内容的提问来源于stack exchange,提问作者Diego Tavares
相关产品推荐
相关产品推荐

