【问题标题】:Importing modules in Typescript vs NodeJs在 Typescript 与 NodeJs 中导入模块
【发布时间】:2021-11-28 21:20:30
【问题描述】:

我正在使用 Discord.js 和 Typescript(我是 Typescript 的新手)创建一个 Discord 机器人,并且正在制作一个命令处理程序。如果我使用的是 NodeJs,我会这样做:

const commandFiles = fs.readdirSync('./src/commands/').filter(file => file.endsWith('.ts'))

for (const file of commandFiles) {
    const command = require(`./src/commands/${file}`)
    commands.set(command.name, command)
}

但我想知道如何处理 Typescript。我试过这样做:

const commandFiles = fs.readdirSync('./src/commands/').filter(file => file.endsWith('.ts'))

for (const file of commandFiles) {
    import(`./src/commands/${file}`).then(command => {
        commands.set(command.name, command)
    })
}

但我最终遇到了同样的错误:Error: Cannot find module './src/commands/pet.ts'。我知道这不是目录的问题。这是pet.ts中的代码:

export default {
    name: 'pet',
    description: 'description',
    async execute({ interaction }) {
        // doing stuff
    }
}

如果这有帮助,这是我的tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "rootDir": "./src",
        "esModuleInterop": true,
        "forceConsistentCasingInFileNames": true,
        "strict": true,
        "noImplicitAny": false,
        "skipLibCheck": true
    },
    "include": ["src"]
}

【问题讨论】:

  • 不要编辑你解决了它。但是,您可以发布您如何解决它作为答案。

标签: typescript discord.js


【解决方案1】:
const commandFiles = fs.readdirSync('./src/commands/').filter(file => file.endsWith('.ts'))
    
    for (const file of commandFiles) {
        const command = ( import(`./src/commands/${file}`) ).default
        commands.set(command.name, command)
        })
    } 

看看这是否有效

【讨论】:

    猜你喜欢
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 2018-06-21
    • 2013-08-09
    • 2012-11-03
    • 2020-06-06
    相关资源
    最近更新 更多