NestJS导入PassportStrategy报错求助:找不到模块'../../lib'
NestJS PassportStrategy 导入报错问题解决
报错详情
编译时触发如下错误:
node_modules/@nestjs/passport/test/common/jwt.strategy.ts:3:34 - error TS2307: Cannot find module '../../lib' or its corresponding type declarations.
3 import { PassportStrategy } from '../../lib';
我的代码实现
import { ConfigService } from '@nestjs/config'; import { ExtractJwt, Strategy } from 'passport-jwt'; import { PassportStrategy } from '@nestjs/passport'; export class JwtStrategy extends PassportStrategy(Strategy) { constructor(config: ConfigService) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: config.get('JWT_SECRET'), }); } }
项目依赖配置
"dependencies": { "@nestjs/common": "^9.0.0", "@nestjs/config": "^2.2.0", "@nestjs/core": "^9.0.0", "@nestjs/jwt": "^9.0.0", "@nestjs/passport": "^9.0.0", "@nestjs/platform-express": "^9.0.0", "@nestjs/swagger": "^6.1.4", "@prisma/client": "^4.8.0", "argon2": "^0.30.2", "class-transformer": "^0.5.1", "class-validator": "^0.14.0", "passport": "^0.6.0", "reflect-metadata": "^0.1.13", "rimraf": "^3.0.2", "rxjs": "^7.2.0" }, "devDependencies": { "@nestjs/cli": "^9.0.0", "@nestjs/schematics": "^9.0.0", "@nestjs/testing": "^9.0.0", "@types/express": "^4.17.13", "@types/jest": "28.1.8", "@types/node": "^16.0.0", "@types/passport-jwt": "^3.0.8", "@types/supertest": "^2.0.11", "@typescript-eslint/eslint-plugin": "^5.0.0", "@typescript-eslint/parser": "^5.0.0", "eslint": "^8.0.1", "eslint-config-prettier": "^8.3.0", "eslint-plugin-prettier": "^4.0.0", "jest": "28.1.3", "prettier": "^2.3.2", "prisma": "^4.8.0", "source-map-support": "^0.5.20", "supertest": "^6.1.3", "ts-jest": "28.0.8", "ts-loader": "^9.2.3", "ts-node": "^10.0.0", "tsconfig-paths": "4.1.0", "typescript": "^4.7.4" }
问题原因及解决方法
这个报错并非你的代码问题,而是TypeScript编译时错误包含了node_modules中@nestjs/passport的测试文件——该测试文件的相对导入路径仅适用于包内部,在你的项目环境下无法解析。
解决步骤:
检查
tsconfig.json配置
确保exclude字段包含node_modules,include仅指向你的源码目录(如src/**/*),示例配置:{ "compilerOptions": { // 其他原有配置... }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] }清理缓存与重新安装依赖
删除旧的依赖和编译产物,重新安装依赖:rm -rf node_modules dist npm install验证编译命令
确保使用NestJS默认的start或build命令,避免自定义命令错误包含了node_modules目录。
内容的提问来源于stack exchange,提问作者Ziya Karagöz
相关产品推荐
相关产品推荐

