使用Redux TS Vite模板时为何出现找不到@reduxjs/toolkit模块错误?
React-Redux + TypeScript 项目依赖找不到问题排查
我对React-Redux较为熟悉,目前正尝试结合TypeScript(TS)进行开发。使用Redux团队推荐的命令 npx degit reduxjs/redux-templates/packages/vite-template-redux my-app 创建TS项目后,从项目创建完成开始就遇到错误提示:Cannot find module '@reduxjs/toolkit' or its corresponding type declarations。此前开发非TS的React-Redux项目时从未遇到过该错误,且尝试多种方式创建项目后仍出现相同问题。查阅资料后得知该问题与依赖及配置文件有关,以下是我的相关配置文件内容:
tsconfig.json
{ "compilerOptions": { "target": "ESNext", "useDefineForClassFields": true, "lib": ["DOM", "DOM.Iterable", "ESNext"], "allowJs": false, "skipLibCheck": true, "esModuleInterop": false, "allowSyntheticDefaultImports": true, "strict": true, "module": "ESNext", "moduleResolution": "bundler", // 我试过改成node和node16 "resolveJsonModule": true, "isolatedModules": true, "noEmit": true, "jsx": "react-jsx", "types": ["vite/client"], // 原来这里是vitest/globals,因为有错误所以改了 "baseUrl": "./", // 我加了baseUrl和paths,但没用 "paths": { "@/*": ["./src/*"] } }, "include": ["vite.config.ts"], // 加了这个,没效果 "references": [{ "path": "./tsconfig.node.json" }] }
tsconfig.node.json
{ "compilerOptions": { "composite": true, "module": "ESNext", "moduleResolution": "bundler", // 我也试过改成node "allowSyntheticDefaultImports": true }, "include": ["vite.config.ts"] }
vite.config.ts
import { defineConfig } from "vitest/config" // 这里也有问题,找不到模块 import react from "@vitejs/plugin-react" // 这个也找不到模块 export default defineConfig({ plugins: [react()], server: { open: true, }, test: { globals: true, environment: "jsdom", setupFiles: "src/setupTests", mockReset: true, }, resolve: { // 我加了resolve和alias,希望能解决问题 alias: { '@' : './src/*', }, }, })
package.json
{ "name": "vite-template-redux", "private": true, "version": "0.0.0", "type": "module", "scripts": { "dev": "vite", "start": "vite", "build": "tsc && vite build", "preview": "vite preview", "test": "vitest run", "format": "prettier --write .", "lint": "eslint .", "lint:fix": "eslint --fix .", "type-check": "tsc --noEmit" }, "dependencies": { "@reduxjs/toolkit": "^2.0.1", "react": "^18.2.0", "react-dom": "^18.2.0", "react-redux": "^9.1.0" }, "devDependencies": { "@testing-library/dom": "^9.3.4", "@testing-library/jest-dom": "^6.2.0", "@testing-library/react": "^14.1.2", "@testing-library/user-event": "^14.5.2", "@types/react": "^18.2.47", "@types/react-dom": "^18.2.18", "@vitejs/plugin-react": "^4.2.1", "eslint": "^8.56.0", "eslint-config-prettier": "^9.1.0", "eslint-config-react-app": "^7.0.1", "eslint-plugin-prettier": "^5.1.3", "jsdom": "^23.2.0", "prettier": "^3.2.1", "typescript": "^5.3.3", "vite": "^5.0.11", "vitest": "^1.2.0" } }
内容的提问来源于stack exchange,提问作者The wandering student
相关产品推荐
相关产品推荐

