如何在混合 JS/TS 项目中运行调试器并将 .ts 导入到 .js?

问题描述 投票:0回答:1

我正在为 Node 编写一个大型 JS 项目的代码,但我想在其中使用 TS。 这是纯粹的 tsc,没有捆绑程序。 所以我遇到的情况是有一个条目

app.js
文件导入
module1.ts
。运行时一切正常,但我无法在 VS Code 中运行实时调试器。我尝试了几种方法:

  1. 如果我尝试
const q =  require('./module1');

我明白了

error Exception has occurred: Error: Cannot find module './module1'
  1. 如果我尝试
const q =  require('./module1.ts');

我明白了

Exception has occurred: ...\module1.ts:1
export default () => {
^^^^^^
  1. 如果我尝试
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
  }
}

它可以以任何方式调试吗?

typescript tsconfig
1个回答
0
投票

调试前是否编译过?

如果存在名为“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文件里就可以了

© www.soinside.com 2019 - 2024. All rights reserved.