Next.js Discord

Discord Forum

Dynamically load files/modules from a directory

Unanswered
Bahama Woodstar posted this in #help-forum
Open in Discord
Avatar
Bahama WoodstarOP
Hello Everyone,
I'm currently developing a command (plugin) handler for my nextjs API to eliminate the use of switch statements.
For that I have to load/import files/modules from a specific directory that is inside /src/lib/command/commands.
The problem is now that every single time i wan't to load the module it says "MODULE NOT FOUND, {path_to_module}" but the weird thing is that the module exists on the exact same path. The file is just a class with default export.

Does someone understand the reason why the module cannot be found/imported even if it the path and every thing else is correct?

13 Replies

Avatar
Barbary Lion
It happens a lot in the react-slick library too. can you share the code so I can have a look?
Avatar
Bahama WoodstarOP
  public async loadCommands(): Promise<void> {
    const directories = readdirSync(this.basePath);
  
    for (const dir of directories) {
      const fullPath = join(this.basePath, dir);
      if (!lstatSync(fullPath).isDirectory()) continue;
  
      const files = readdirSync(fullPath).filter((file) => file.endsWith('.ts'));
  
      for (const file of files) {
        const filePath = join(fullPath, file);
        console.log('Loading Command from:', filePath); // Debug: print the file path
  
        try {
          const commandModule = await import(filePath) as ESModule;
          const CommandClass = commandModule.default;
  
          if (CommandClass instanceof BaseCommand) {
            throw new TypeError(`Module ${filePath} does not default export a class`);
          }
  
          const commandInstance = new CommandClass();
          const commandKey = `${commandInstance.chain}:${commandInstance.nodeType}:${commandInstance.name}`;
          this.commands.set(commandKey, commandInstance);
        } catch (error) {
          console.error(`Failed to load command from ${filePath}:`, error);
        }
      }
    }
  }
Avatar
Bahama WoodstarOP
@Barbary Lion here
Avatar
Barbary Lion
try this
Image
I added some error handlers, I hope it works 🙂
Avatar
Bahama WoodstarOP
Module not found
Avatar
Barbary Lion
I tried but sorry I can't think any more of it😅. checked the code few times. it should be working.
Avatar
Bahama WoodstarOP
Did you test it in a nextjs env?
I think theres a problem with webpack that it does not include the /commands folder
or not compiling them
Avatar
Askar
Next.js is kinda limited there
Avatar
Bahama WoodstarOP
Is there a way to init a singletone directly when starting the application without being dependet of any requests made?
Avatar
Bahama WoodstarOP
I'm using Page router currenlty because now upgrading our codebase would take ages.

Is it maybe possible with app router?