【发布时间】:2021-04-09 16:12:49
【问题描述】:
我有另一个使用 typescript 和 global.d.ts 文件构建的 NodeJS 应用程序,一切正常,但我的新应用程序在使用 ts-node-dev ts-main-file.ts 运行时出错
在新应用程序中,我在 src 文件夹中有 global.d.ts 文件,但无法识别。
global.d.ts 文件内容
declare namespace NodeJS {
export interface Global {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
sequelize: any;
}
}
tsconfig.json 文件内容
{
"extends": "@tsconfig/node14/tsconfig.json",
"compilerOptions": {
"resolveJsonModule": true,
"preserveConstEnums": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"noFallthroughCasesInSwitch": true,
"allowSyntheticDefaultImports": true,
"outDir": "out/build",
"types": ["reflect-metadata"]
},
"include": ["src/**/*", "tests/**/*"],
"exclude": ["node_modules", "**/*.spec.ts"]
}
我不知道为什么它不起作用,但如果有人能指出缺失的部分,那将更有帮助。
环境细节: 节点 JS 15 ts-node-dev 版本。 1.1.1(使用 ts-node 版本 9.1.1,打字稿版本 4.1.3) Linux(流行操作系统 20.10)
我看到错误的文件的代码 sn-p:
async connectWithDB() {
const databaseName = 'local_server';
const userName = 'test';
const password = 'Test123$';
const host = 'localhost';
const dialect = 'postgres';
global.sequelize = new Sequelize(databaseName, userName, password, {
host: host,
dialect: dialect,
pool: {
max: 50,
min: 0,
acquire: 30000,
idle: 10000,
},
define: {
charset: 'utf8',
},
});
try {
await global.sequelize.authenticate();
console.log('Connection has been established successfully.');
} catch (error) {
console.error('Unable to connect to the database:', error);
process.exit(1);
}
}
【问题讨论】:
-
您提供的信息不够,请在您的描述中提供相关文件或模块的内容,如:
ts-main-file.ts编辑。也许您使用了this或type: GlobalThis的未定义属性,它没有被 VS-Code/IDE 捕获,但您在编译时仍然遇到错误。请记住,浏览器和 NodeJ 的全局this是不同的 -
使用 ts-main-fie.ts 的代码 sn-p 编辑答案
-
在上面的代码 sn-p 如果我从
global.sequelize更改为const sequelize = ....那么一切正常 -
global.d.ts在哪里?是在src下吗?目前尚不清楚您为什么要使用include.... -
global.d.ts 直接放在src文件夹下。我们不需要
include指向 src 目录以供打字稿查看吗?
标签: node.js typescript