我把一个Discord bot项目从JavaScript切换到了TypeScript。
但是运行编译后的代码(使用tcs
),redis
模块是undefined
。编译过程成功,其他模块(discord.js
,dotenv
等)导入并使用得很好,需要redis
模块工作,但输出undefined
。
我的tsconfig.json
(基于@tsconfig/node 16):
{
"extends": "@tsconfig/node16/tsconfig.json",
"compilerOptions": {
"rootDir": "./src/",
"outDir": "./dist/",
"importHelpers": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"removeComments": true,
"typeRoots": [
"node_modules/@types"
],
"sourceMap": false,
"baseUrl": "./"
},
"files": [
"src/index.ts"
],
"include": [
"./**/*.ts"
],
"exclude": [
"node_modules",
"dist"
]
}
我尝试了很多方法,包括删除typeRoots
和exclude
。
我的package.json
:
{
"name": "discord-bot",
"version": "0.1.0",
"description": "A bot to manage roles and such on Discord",
"main": "index.js",
"scripts": {
"start": "tsc && node dist/index.js",
"build": "tsc",
},
"dependencies": {
"@tsconfig/node16": "^16.1.0",
"@types/node": "^16.9.0",
"discord.js": "^14.11.0",
"dotenv": "^16.3.1",
"redis": "^4.6.7",
"typescript": "^5.1.6"
}
}
所有依赖项都已更新到最新版本并支持NodeJS 16。
我的代码开始:
import Discord from "discord.js"
import redis from "redis"
import http from "http"
import "dotenv/config"
import * as process from "process"
// Initialise Discord Client
const discordClient: Discord.Client<true> = new Discord.Client({
intents: [
Discord.GatewayIntentBits.Guilds,
Discord.GatewayIntentBits.GuildMessages,
Discord.GatewayIntentBits.GuildIntegrations
]
})
// Create the database client
const redisClient = redis.createClient()
在最后一行,我在运行时得到了一个TypeError: Cannot read properties of undefined (reading 'createClient')
,即使编译工作正常,我的IDE自动完成了库功能。
(请注意,我仍然是Node上下文中TypeScript的初学者,来自React TypeScript框架)
1条答案
按热度按时间4xrmg8kj1#
基于他们的Redis文档,这是我在他们的片段上看到的
在从
node_modules/redis/dist/index.d.ts
检查它们的类型定义时,我发现没有默认的导出,所以尝试使用命名的导出或为它们创建所有别名import * as redis from 'redis'