我正在为 Node 编写一个大型 JS 项目的代码,但我想在其中使用 TS。 这是纯粹的 tsc,没有捆绑程序。 所以我遇到的情况是有一个条目
app.js
文件导入 module1.ts
。运行时一切正常,但我无法在 VS Code 中运行实时调试器。我尝试了几种方法:
const q = require('./module1');
我明白了
error Exception has occurred: Error: Cannot find module './module1'
const q = require('./module1.ts');
我明白了
Exception has occurred: ...\module1.ts:1
export default () => {
^^^^^^
import q from './module1';
我明白了
(node:1092) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
import q from './module1';
^^^^^^
tsconfig.json:
{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"sourceMap": true,
"outDir": "./build",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true
}
}
它可以以任何方式调试吗?
调试前是否编译过?
如果存在名为“module1.js”的 Javascript 文件,则不会出现第一个错误信息。
您可以为调试器编写配置文件,以避免手动编译。
// .vscode/tasks.json
{
"version": "2.0.0",
"tasks": [
{
"type": "shell",
"command": "tsc",
"label": "Compile TypeScript"
}
]
}
//.vscode/launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\src\\main.js",
"preLaunchTask": "Compile TypeScript"
}
]
}
你的ts文件是用esm编写的,而nodejs默认使用cjs,所以你会看到第二个和第三个错误信息。如果你把cjs写在ts文件里就可以了