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

运行yarn run package时报.ts文件扩展名未知错误求助

运行yarn run package时报错TypeError [ERR_UNKNOWN_FILE_EXTENSION],无法识别gulpfile.ts的.ts扩展名

问题详情

  • 执行yarn run package时触发错误:TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /xxx/gulpfile.ts
  • 尝试添加NODE_OPTIONS="--loader ts-node/esm"参数后问题依旧
  • 已尝试修改tsconfig的target配置,也排查过相关issue,均未解决

环境信息

  • Node.js: 18.12.1
  • npm: 9.1.3
  • Yarn: 3.3.0

配置文件

package.json

...
"scripts": {
    "build": "tsc",
    "build:production": "npm run prestart && npm prune --production",
    "watch": "tsc --w",
    "prestart": "npm run build && func extensions install",
    "start:host": "func start",
    "start": "npm-run-all --parallel start:host watch",
    "test": "echo \"No tests yet...\"",
    "package": "gulp build && gulp package"
  },
  "description": "",
  "devDependencies": {
    "@azure/functions": "^1.0.1-beta1",
    "@types/gulp": "^4.0.9",
    "@types/gulp-zip": "^4.0.2",
    "@types/node": "^18.11.13",
    "del": "^7.0.0",
    "gulp-typescript": "^6.0.0-alpha.1",
    "gulp-zip": "^5.1.0",
    "npm-run-all": "^4.1.5",
    "ts-node": "^10.2.1",
    "typescript": "^3.3.3"
  },
  "dependencies": {
    "azure-devops-node-api": "^11.2.0",
    "gulp": "^4.0.2"
  },
  "resolutions": {
    "decode-uri-component": "0.2.2",
    "glob-parent": "6.0.2",
    "qs": "6.10.3",
    "string_decoder": "1.3.0"
  }

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "moduleResolution": "node",
    "target": "es6",
    "outDir": "dist",
    "rootDir": ".",
    "sourceMap": true,
    "noImplicitAny": true,
    "strict": false,
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "lib": [
      "es6"
    ]
  },
  "exclude": [
    "./gulpfile.ts"
  ],
  "ts-node": {
    "esm": true
  }
}

解决方案

1. 直接用ts-node启动gulp

修改package.json中的package脚本,让ts-node负责解析gulpfile.ts:

"package": "ts-node --esm node_modules/gulp/bin/gulp.js build package"

如果需要分开执行两个任务:

"package": "ts-node --esm node_modules/gulp/bin/gulp.js build && ts-node --esm node_modules/gulp/bin/gulp.js package"

2. 修正tsconfig的冲突配置

当前tsconfig中module: commonjs和ts-node.esm: true存在冲突,二选一调整:

  • 方案A:关闭ts-node的ESM模式,适配commonjs
    "ts-node": {
      "esm": false,
      "transpileOnly": true
    }
    
  • 方案B:切换项目为ESM模式(需测试依赖兼容性)
    • 在package.json中添加"type": "module"
    • 修改tsconfig的compilerOptions.module为ESNext

3. 升级依赖版本

当前ts-node和TypeScript版本较旧,与Node 18兼容性不佳:

  • 升级ts-node到最新稳定版(如^10.9.1)
  • 升级TypeScript到4.x或5.x版本(如^4.9.5或^5.3.3)

4. 取消排除gulpfile.ts

tsconfig中排除了gulpfile.ts,导致ts-node无法正确解析它,调整exclude配置:

"exclude": [
  "dist"
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 19:50:25