我对类型记录有点陌生,我在其他人现有存储库的分支中工作,试图针对它运行测试。
摘要
我编写了一个测试脚本examples/test.ts,并试图使用vscode调试器对其进行调试。当我使用ts-node ./examples/test.ts运行脚本时,脚本将成功执行。但是,当我尝试使用vscode调试器运行它时,我得到了著名的SyntaxError: Cannot use import statement outside a module。这个错误发生在我的类型记录测试的第1行,在这里我第一次尝试import {Foo} from '../dist',其中Foo是被测试的对象。
尝试修复
我已经研究了一段时间了,最常见的修复方法似乎是将module设置为tsconfig.json compilerOptions中的commonjs。但是,这个项目已经有了正确的设置。
另一种常见的修复方法是在package.json中设置"type":"module",但是当我这样做时,会在vscode调试器中引发新的错误。具体来说,Uncaught TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /path/truncated/by/me/examples/test.ts.我可以在调试器之外正常运行脚本这一事实使我认为它更有可能是tsconfig.json或类似的配置,当然,我可能错了。
相关配置文件:
.vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}/examples/test.ts",
"preLaunchTask": "tsc: build - tsconfig.json",
"outFiles": [
"${workspaceFolder}/dist/**/*.js"
]
}
]
}tsconfig.json
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"lib": ["es2015", "dom"],
"allowJs": true,
"skipLibCheck": true,
"sourceMap": true,
"outDir": "dist",
"strict": true,
"noImplicitAny": true,
"moduleResolution": "node",
"baseUrl": "./",
"esModuleInterop": true
},
"include": ["*"],
"exclude": ["node_modules"]
}版本
在最新的VSCode上运行macOS 1.52.1。ts-node --version给出了v9.1.1,该项目使用node --version of v12.14.1。
发布于 2021-11-04 04:23:26
我确实遇到了问题。下面是我的cli项目(使用vscode 1.61.2)的最终效果。
launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Program",
"program": "${workspaceFolder}/src/cli.ts",
"request": "launch",
"preLaunchTask": "npm: build",
"skipFiles": ["<node_internals>/**"],
"type": "pwa-node"
}
]
}tsconfig.json:
{
"compilerOptions": {
"target": "ES2020" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */,
"module": "commonjs" /* Specify what module code is generated. */,
"esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */,
"forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */,
"strict": true /* Enable all strict type-checking options. */,
"skipLibCheck": true /* Skip type checking all .d.ts files. */,
"outDir": "./lib",
"importHelpers": false,
"sourceMap": true
}
}package.json脚本部分:
"scripts": {
"start": "node lib/cli.js",
"build": "tsc"
},package.json devDependencies
"devDependencies": {
"@types/node": "^16.11.6",
"typescript": "^4.4.4"
},https://stackoverflow.com/questions/65907577
复制相似问题