导入不存在的常量时TypeScript编译器未报错问题求助
TypeScript Node应用运行时输出undefined,编译与Lint均无报错
我用TypeScript开发Node应用,执行npm run dev时代码能正常转译运行,但控制台输出undefined。相关代码如下:
index.ts:
import { a } from './some-file.ts'; console.log(`the value of a is: ${a}`);
some-file.ts:
export const b = 2;
奇怪的是,执行npm run lint也没检测到任何异常。以下是我的配置文件:
package.json
{ "name": "backend", "version": "1.0.0", "description": "", "main": "index.js", "watch": { "lint": { "patterns": [ "src" ], "extensions": "ts", "quiet": false } }, "scripts": { "build": "npx tsc", "start": "npm run build && node dist/index.js", "dev": "tsx watch src/index.ts", "test": "echo \"Error: no test specified\" && exit 1", "lint": "npx eslint src/", "lint:watch": "npm-watch lint" }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "dotenv": "^16.4.5", "express": "^4.19.2", "kysely": "^0.27.4", "pg": "^8.12.0" }, "devDependencies": { "@eslint/js": "^9.5.0", "@types/express": "^4.17.21", "eslint": "^8.57.0", "globals": "^15.6.0", "npm-watch": "^0.13.0", "tsx": "^4.15.7", "typescript": "^5.5.2", "typescript-eslint": "^7.14.1" } }
tsconfig.json
{ "compilerOptions": { "target": "ESNext", "module": "ESNext", "rootDir": "./src", "moduleResolution": "node", "resolveJsonModule": true, "outDir": "./dist", "esModuleInterop": true, "strict": true, "skipLibCheck": true } }
问题根源与解决办法
1. 代码本身的错误
最直接的问题是你在index.ts里导入了some-file.ts中不存在的a,而该文件只导出了b。运行时Node找不到对应的导出值,自然输出undefined。
2. 为什么编译和Lint没报错?
- TypeScript转译不做类型检查:你用
tsx watch启动开发服务,tsx默认只负责快速转译TypeScript到JavaScript,不会执行完整的类型检查。哪怕tsconfig.json开了strict: true,tsx也不会触发类型校验,所以没发现导入错误。 - ESLint规则未配置到位:虽然你装了
typescript-eslint,但没启用检测无效导入的规则,导致Lint过程没发现问题。
3. 修复步骤
第一步:修正代码
把index.ts的导入语句改成正确的:
import { b } from './some-file.ts'; console.log(`the value of b is: ${b}`);
或者在some-file.ts中导出a:
export const b = 2; export const a = 1; // 新增导出
第二步:让TypeScript在开发时做类型检查
修改package.json里的dev脚本,在启动tsx前先执行TypeScript类型检查:
"dev": "tsc --noEmit && tsx watch src/index.ts"
tsc --noEmit会执行完整的类型检查但不生成编译文件,这样每次修改代码都会先校验类型,提前发现这类错误。
第三步:配置ESLint检测无效导入
创建或修改.eslintrc.cjs文件,启用相关规则:
module.exports = { root: true, parser: '@typescript-eslint/parser', plugins: ['@typescript-eslint'], extends: [ 'eslint:recommended', 'plugin:@typescript-eslint/recommended' ], rules: { '@typescript-eslint/no-unused-vars': 'error', 'import/named': 'error' } };
这样ESLint就能检测到导入不存在的导出项这类问题了。
内容的提问来源于stack exchange,提问作者Marcus Junius Brutus
相关产品推荐
相关产品推荐

