[英]Importing modules in Typescript vs NodeJs
我正在使用 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'
了同样的错误: 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"]
}
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)
})
}
看看这是否有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.