如何在Angular 15项目的VSCode中测试无Angular依赖的TypeScript代码?
SyntaxError: Cannot use import statement outside a module
修改`package.json`添加`"type": "module"`后又出现新错误:
TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /.../test.spec.ts
请问有没有可行方法,能像在Node项目中那样,在VSCode中测试无Angular依赖的TypeScript代码? # 可行解决方案 ## 方法1:适配Angular ES模块规范调整launch.json Angular 15默认采用ES模块规范,旧的`ts-node/register`仅支持CommonJS,需改用`ts-node/esm`并调整配置参数: ```json { "version": "0.2.0", "configurations": [ { "name": "Current TS Spec (Angular)", "type": "node", "request": "launch", "args": ["${relativeFile}"], "runtimeArgs": [ "--nolazy", "--experimental-specifier-resolution=node", "-r", "ts-node/esm" ], "sourceMaps": true, "cwd": "${workspaceRoot}", "env": { "TS_NODE_PROJECT": "./tsconfig.spec.json" }, "resolveSourceMapLocations": [ "${workspaceFolder}/**", "!**/node_modules/**" ] } ] }
- 关键说明:
ts-node/esm:提供ES模块下的TS编译支持--experimental-specifier-resolution=node:解决ES模块模式下文件扩展名的解析问题TS_NODE_PROJECT:指定使用Angular自带的测试TS配置,保证编译规则和项目一致resolveSourceMapLocations:让VSCode正确识别源映射文件,方便断点调试
方法2:为测试文件单独配置CommonJS模式
如果不想改动全局模块规范,可以创建专属的CommonJS配置文件tsconfig.test.cjs.json:
{ "extends": "./tsconfig.json", "compilerOptions": { "module": "CommonJS", "target": "ES2020", "esModuleInterop": true }, "include": ["src/**/*.spec.ts"] }
再修改launch.json指定该配置:
{ "version": "0.2.0", "configurations": [ { "name": "Current TS Spec (CJS)", "type": "node", "request": "launch", "args": ["${relativeFile}"], "runtimeArgs": ["--nolazy", "-r", "ts-node/register"], "sourceMaps": true, "cwd": "${workspaceRoot}", "env": { "TS_NODE_PROJECT": "./tsconfig.test.cjs.json" } } ] }
这样测试文件会以CommonJS模式运行,避开ES模块的兼容性问题。
方法3:用Jest单独运行(项目已集成Jest时)
如果Angular项目已经配置了Jest,可直接在终端执行单个测试文件:
npx jest ${relativeFile} --watch
如需调试,添加--inspect-brk参数后,用VSCode的「Attach to Node Process」配置连接调试即可。
内容的提问来源于stack exchange,提问作者Picci
相关产品推荐
相关产品推荐

