Vite中npm run dev无法检测未定义名称的技术问询
Vite React+TypeScript项目中npm run dev未检测未定义变量的解决方法
问题描述
使用Vite创建的React+TypeScript项目里,npm run dev运行时无法检测到未定义的变量/函数(比如调用不存在的does_not_exist()),但执行npm run build时能正常报错。需要在开发阶段(保留热更新功能)就能检测这类错误。
复现步骤
- 创建React/TypeScript项目:
$ npm create vite@latest Need to install the following packages: create-vite@5.5.2 Ok to proceed? (y) y ✔ Project name: … foobar ✔ Select a framework: › React ✔ Select a variant: › TypeScript
- 进入项目并安装依赖:
cd foobar && npm i
- 修改
src/main.tsx,添加未定义函数调用:
import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import App from './App.tsx' import './index.css' does_not_exist(); createRoot(document.getElementById('root')!).render( <StrictMode> <App /> </StrictMode>, )
- 执行
npm run dev,项目正常启动无错误提示;执行npm run build则会报错提示does_not_exist未定义。
解决方法
1. 安装并配置vite-plugin-checker插件
这个插件能在开发服务器运行时实时执行TypeScript类型检查和ESLint检查,且不影响热更新功能。
- 安装依赖:
npm install vite-plugin-checker --save-dev
- 修改
vite.config.ts,添加插件配置:
import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' import checker from 'vite-plugin-checker' export default defineConfig({ plugins: [ react(), checker({ // 开启TypeScript类型检查 typescript: true, // 配置ESLint检查(需确保已安装ESLint及相关插件) eslint: { lintCommand: 'eslint "./src/**/*.{ts,tsx}"' } }) ] })
2. 开启TypeScript严格模式
修改tsconfig.json,确保strict选项为true,让TypeScript进行更严格的类型检查:
{ "compilerOptions": { "strict": true, // 其他原有配置... } }
3. 配置ESLint检查未定义变量
如果项目未配置ESLint,先安装依赖:
npm install eslint @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint-plugin-react --save-dev
然后创建.eslintrc.cjs配置文件:
module.exports = { env: { browser: true, es2021: true, node: true }, extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended', 'plugin:react/recommended' ], parser: '@typescript-eslint/parser', parserOptions: { ecmaFeatures: { jsx: true }, ecmaVersion: 'latest', sourceType: 'module' }, plugins: ['@typescript-eslint', 'react'], rules: { // 强制检测未定义变量 '@typescript-eslint/no-undef': 'error' } }
原理说明
Vite开发服务器默认用ESBuild做代码转换,ESBuild为追求速度仅做语法层面转换,不会执行完整的TypeScript类型检查。而npm run build会触发tsc --noEmit检查,因此能检测到未定义变量。通过vite-plugin-checker可在开发阶段同时启动TypeScript和ESLint检查服务,实时反馈错误,且不影响热更新体验。
内容的提问来源于stack exchange,提问作者Marcus Junius Brutus
相关产品推荐
相关产品推荐

