You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将tsc编译脚本配置为npm脚本?解决TS6053文件未找到错误

npm脚本执行tsc命令报错:找不到src/*.ts文件

问题

我尝试将以下命令作为npm脚本运行:

tsc src/*.ts --outDir bin

终端直接执行该命令完全正常,但将其添加到package.json的scripts后:

{
  "scripts": {
    "compile": "tsc src/*.ts --outDir bin"
  }
}

执行npm run compile时出现错误:

error TS6053: File 'src/*.ts' not found.
  The file is in the program because:
    Root file specified for compilation

当前tsconfig.json配置:

// tsconfig.json
{
  "compilerOptions": {
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "noFallthroughCasesInSwitch": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "removeComments": true,
    "allowJs": true,
    "checkJs": true,

    "module": "esnext",
    "esModuleInterop": true,
    "target": "ESNext",
    "moduleResolution": "node",
    "sourceMap": true,
    "outDir": "./bin",
    "rootDir": "src"
  },
  "include": ["src/*.ts", "src/*", "src/**/*", ".env"],
  "exclude": ["src/views"]
}

当前package.json配置:

//package.json
{
  "name": "auth-node-with-sql",
  "version": "1.0.0",
  "description": "Program written to learn basic concepts of authorization and authentication using node and express",
  "main": "bin/server.js",
  "scripts": {
    "compile": "tsc src/*.ts --outDir bin",
    "lint": "npx eslint . --ext .ts",
    "start": "node bin/server.js"
  },
  "repository": {
    "type": "git",
    "url": "auth-node-with-sql"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/mysql": "^2.15.21",
    "@typescript-eslint/eslint-plugin": "^5.50.0",
    "@typescript-eslint/parser": "^5.50.0",
    "eslint": "^8.33.0",
    "typescript": "^4.9.5"
  },
  "dependencies": {
    "@types/express": "^4.17.16",
    "axios": "^1.3.1",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "express-session": "^1.17.3",
    "mysql": "^2.18.1"
  },
  "type": "commonjs"
}

目录结构:

bin
node_modules
src
  /db
  /utilities
  /src.ts
.env
.gitignore
package-lock.json
package.json
tsconfig.json

原因

npm脚本中,通配符*不会被系统Shell自动展开,而是直接作为字符串传递给tsc命令。但tsc本身不支持解析Shell风格的通配符,因此会把src/*.ts当作一个具体的文件名去查找,自然找不到对应的文件。

解决方案

方案1:利用tsconfig.json配置(推荐,跨平台)

你的tsconfig.json已经配置了include规则和outDir输出目录,只需修改两个地方:

  1. 修改tsconfig.json中的noEmit选项为false(当前设置为true会阻止tsc生成编译文件):
"compilerOptions": {
  // ...其他配置
  "noEmit": false
}
  1. 修改package.json的scripts,直接调用tsc即可,它会自动读取tsconfig.json的配置:
"scripts": {
  "compile": "tsc",
  // ...其他脚本
}

这种方式不仅解决了通配符问题,还能编译src目录下所有子文件夹中的文件(比如src/db、src/utilities里的文件),比原命令覆盖范围更完整。

方案2:强制Shell展开通配符(仅适用于类Unix系统)

如果一定要保留原命令的写法,可以通过bash -c让Shell先解析通配符:

"scripts": {
  "compile": "bash -c 'tsc src/*.ts --outDir bin'"
}

但这种方法不支持Windows系统,不推荐跨平台项目使用。

内容的提问来源于stack exchange,提问作者Anthony Zuech

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 15:00:53