我想在 Visual Studio 2022(不是 Visual Studio Code)项目中开发一个 nodeJS 脚本。
我有一个 ASP.NET Core C# 项目。
在该项目中,我有一个文件夹 TypeScript。
在打字稿中,我有几个子文件夹,我在其中开发打字稿脚本,这些脚本被转换为 /wwwroot/ts/
现在,除了浏览器的所有这些 JS 之外,我想为 NodeJS 创建一个 JS(一个控制台测试应用程序)。
我真的很难弄清楚如何在 tsconfig.json 中配置它
我有以下 main.ts 文件:
// Define the main function, and make it async
async function main(): Promise<void>
{
// Process command-line arguments (starts from index 2, since first two args are 'node' and the script path)
const args = process.argv.slice(2);
if (args.length === 0)
{
console.log("Hello, World!");
} else
{
console.log(`Hello, ${args[0]}!`);
}
// Simulate async operation, like a delay
await new Promise(resolve => setTimeout(resolve, 1000));
console.log("Finished ! ");
}
// Call the async main function
main().then(() =>
{
// Exit with success code 0
process.exit(0);
}).catch(err =>
{
console.error("An error occurred:", err);
process.exit(1);
});
然后我有这个 tsconfig.json
{
"compileOnSave": true,
"compilerOptions": {
"target": "ES2015", //"target": "es5",
//"module": "amd", // define, export, like playground
// "module": "commonjs", // require
"module": "Node16",
"types": [ "node" ],
// "module": "commonjs", // just like typescript
// "module": "system", // System.register
// "module": "umd", // factory, require, exports
// "module": "esnext", // like typescript
// "module": "none", // Object.defineProperty, require
// "module": "commonjs",
"lib": [
"ES2020"
],
"noImplicitAny": true,
"noEmitOnError": true,
"removeComments": true,
"sourceMap": false,
"outDir": "../../wwwroot/nodeapp",
"rootDir": "./",
"allowUnreachableCode": true,
"moduleResolution": "node" // Resolve modules using Node.js rules
//,"alwaysStrict ": true,
},
"exclude": [
"node_modules",
"wwwroot"
],
"include": [
"**/*" ]
}
现在通常,我有浏览器:
"lib": [
"DOM",
"ES2016",
"ES2015.Promise",
"ES2015.Proxy"
],
但是对于 NodeJS,我想我可以做类似的事情
"lib": [
"node",
"ES2020"
],
完成了,但这不起作用。 它不会将节点识别为有效的库。
我发现可以完成这项工作的唯一方法是将node.d.ts放入我的文件夹中。 虽然它现在找到了进程,但它无法识别控制台,尽管 node.d.ts 在全局中定义了它。我认为这是因为它不将 global 识别为全局命名空间。而不是在窗口或其他什么地方搜索。
我该如何解决这个问题,这样我就不必编写 global.console ? 难道这个typescript nuget for Visual Studio真的很愚蠢,以至于它不认识到我这次想构建一个nodeJS应用程序,而且也没有办法告诉它?
我真的不想用 npm 手动添加任何东西,因为这会破坏自动构建过程(持续集成系统)。
啊,这是我自己得到的。
首先通过
获取所有需要的d.ts文件git clone https://github.com/DefinitelyTyped/DefinitelyTyped
git clone https://github.com/nodejs/undici
现在复制
DefinitelyTyped/types/node/v20
中的所有类型
到根项目目录中的新文件夹nodev20
。
然后,将 nodev20/index.d.ds
重命名为 nodev20/node.d.ds
现在,将所有文件从
/undici/undici/types
复制到新文件夹 nodev20/undici-types
然后,在 undici 文件夹中,根据需要,通过引用父目录添加节点
/// <reference types="../node" />
现在在
globals.d.ts
文件夹的 nodev20
中,将 undici 的导入替换为
import * as Undici from "./undici-types/index";
然后搜索并替换 import("undici-types")
为 Undici.
.
完成,现在您可以在 VS2022 中获得完整的智能感知支持,而无需 npm。