TypeScript -运行输出文件时未定义`redis`模块

jrcvhitl  于 2023-10-15  发布在  Redis
关注(0)|答案(1)|浏览(110)

我把一个Discord bot项目从JavaScript切换到了TypeScript。
但是运行编译后的代码(使用tcs),redis模块是undefined。编译过程成功,其他模块(discord.jsdotenv等)导入并使用得很好,需要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"
    ]
}

我尝试了很多方法,包括删除typeRootsexclude
我的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框架)

4xrmg8kj

4xrmg8kj1#

基于他们的Redis文档,这是我在他们的片段上看到的

import { createClient } from 'redis';

const client = createClient();

client.on('error', err => console.log('Redis Client Error', err));

await client.connect();

await client.set('key', 'value');
const value = await client.get('key');
await client.disconnect();

在从node_modules/redis/dist/index.d.ts检查它们的类型定义时,我发现没有默认的导出,所以尝试使用命名的导出或为它们创建所有别名import * as redis from 'redis'

相关问题