简体   繁体   English

相对路径导入失败,未找到模块,但绝对路径导入有效

[英]Relative path import fails, module not found, but absolute path import works

I've had this issue for a while now and tried to find fixes for it.我已经有一段时间了这个问题,并试图找到解决办法。 I'm developing my discord.js bot and recently migrated from TS back to JS because of certain problems i've experienced with it.我正在开发我的 discord.js 机器人,最近由于我遇到的某些问题从 TS 迁移回 JS。 Upon migrating, however, I was met with an issue of Node.js not finding my command handler file using relative paths.然而,在迁移时,我遇到了 Node.js 没有使用相对路径找到我的命令处理程序文件的问题。 VSCode resolves the path and suggests me the file, reading the directory with fs.readdir('./commands') also showed the handler file. VSCode 解析路径并向我建议文件,使用fs.readdir('./commands')读取目录还显示了处理程序文件。 So far I've tried:到目前为止,我已经尝试过:

  1. Switching to dynamic import ( await import('...') ) -> didn't work切换到动态导入( await import('...') )-> 不起作用
  2. Removing the first part of the import ( const {... } = ) -> works删除导入的第一部分( const {... } = )-> 有效
  3. Commenting the handler import line off, so Node.js would import the next file -> didn't work, no imports are successful将处理程序导入行注释掉,因此 Node.js 将导入下一个文件-> 不起作用,没有导入成功
  4. Using full path to the handler file ( await import('file://C:/.../emberbot/commands/handler.js') )使用处理程序文件的完整路径( await import('file://C:/.../emberbot/commands/handler.js')

Directory tree:目录树:

emberbot
├── commands
│   ├── config.js
│   ├── convert.js
│   ├── dn.js
│   ├── eval.js
│   ├── exit.js
│   ├── handler.js
│   ├── hi.js
│   ├── info.js
│   ├── minecraft.js
│   ├── pfp.js
│   ├── ping.js
│   ├── poll.js
│   ├── quote.js
│   ├── rcg.js
│   ├── rng.js
│   ├── suggest.js
│   └── talkingben.js
├── config.json
├── index.js
├── misc.json
├── modules
│   ├── ben.js
│   ├── bots-moe.js
│   ├── chatbot.js
│   ├── client.js
│   ├── config.js
│   ├── interfaces.d.ts
│   ├── logger.js
│   └── misc.js
├── package-lock.json
└── package.json

(not full, cleared up of certain garbage that don't relate at all) (未满,清除了某些根本不相关的垃圾)

Full source code: https://github.com/NoNameLmao/emberbot (up to date with this question)完整源代码: https://github.com/NoNameLmao/emberbot (这个问题是最新的)

Since relative paths are processed to the current working directory of your app, and the current working directory being a variable depending on where you start your application, its always advisable to resolve imports to the root file.由于相对路径被处理到应用程序的当前工作目录,并且当前工作目录是一个变量,具体取决于您启动应用程序的位置,因此始终建议将导入解析为根文件。 This is why the absolute import works but the others fail.这就是为什么绝对导入有效但其他导入失败的原因。

Check this answer for some context检查此答案以获取一些上下文

you can use __dirname你可以使用__dirname

Your code becomes你的代码变成

fs.readdir(__dirname + '/commands')

So you code will read所以你的代码会读

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM