Azure Function项目tsconfig.json配置及TS编译失败问题排查
项目目录结构
- azure_functions - function_app - functions - project_1 function.json index.ts package.json package-lock.json tsconfig.json node_modules
配置文件详情
tsconfig.json
{"compilerOptions": { "module": "commonjs", "target": "es5", "outDir": "./dist", "rootDir": "./", "allowJs": true, "strict": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "esModuleInterop": true, "resolveJsonModule": true, "isolatedModules": true }, "include": ["./**/*.ts"], "exclude": ["node_modules", "dist"] }
package.json
{"name": "ts_project", "version": "1.0.0", "description": "", "scripts": { "start": "npm run build && func start", "build": "tsc", "watch": "tsc -w", "prestart": "npm run build && func extensions install", "start:host": "func start", "test": "echo \"No tests yet...\"" }, "dependencies": { "node-fetch": "^2.6.7" }, "devDependencies": { "@azure/functions": "^3.5.0", "@types/node-fetch": "2.6.2", "typescript": "^4.4.4" } }
function.json
{"bindings": [ {"authLevel": "function", "type": "httpTrigger", "direction": "in", "name": "req", "methods": [ "get", "post" ] }, {"type": "http", "direction": "out", "name": "res" } ], "scriptFile": "../dist/functions/project_1/index.js" }
问题现象
运行npm start时,TypeScript未生成JavaScript文件,同时抛出错误:Invalid script file name configuration. The scriptFile property is set to a file it doesn't exist.
但在project_1目录下直接执行tsc index.ts,能正常生成对应的JS文件。需要排查通过package.json脚本无法编译的原因,以及tsconfig.json的缺失配置。
核心原因:noEmit配置阻止编译输出
tsconfig.json中开启了"noEmit": true,这个配置会强制TypeScript编译器不生成任何输出文件。所以执行npm run build(本质是tsc命令)时,即便代码没有语法错误,也不会生成dist目录及对应的JS文件,导致function.json指定的路径找不到文件。
而在project_1目录执行tsc index.ts时,因为直接指定了单个文件编译且未显式指定项目配置,编译器会忽略根目录的tsconfig.json,此时noEmit默认值为false,因此能正常生成JS文件。
修复步骤
关闭
noEmit配置
修改tsconfig.json的compilerOptions,将"noEmit": true改为"noEmit": false,或者直接删除该配置项(默认即为false)。确认目录结构映射正确性
当前rootDir: "./"和outDir: "./dist"的配置是合理的,源码目录结构会完整映射到dist目录下,functions/project_1/index.ts会被编译到dist/functions/project_1/index.js,与function.json中的scriptFile路径匹配,无需调整。验证编译命令
修改完成后,执行npm run build即可生成dist目录下的所有JS文件,再运行npm start就能正常启动Azure Functions。可选:处理
isolatedModules潜在问题
若保留"isolatedModules": true,需确保每个.ts文件都是模块(即包含import/export语句)。如果index.ts没有导出内容,可以添加空导出语句:export {};,避免编译报错。
修复后的tsconfig.json示例
{"compilerOptions": { "module": "commonjs", "target": "es5", "outDir": "./dist", "rootDir": "./", "allowJs": true, "strict": true, "forceConsistentCasingInFileNames": true, "esModuleInterop": true, "resolveJsonModule": true, "isolatedModules": true }, "include": ["./**/*.ts"], "exclude": ["node_modules", "dist"] }
内容的提问来源于stack exchange,提问作者abautista

