0

We have a ES5 project where we used the import-modules library to import all files of a directory and execute there run()-function that I am now migrating to ES6.

...
import importModules from 'import-modules';
const initHooks = importModules('../../hooks/onInitStart');

export const executeInitHooks = async () => {
  logger.info(`Executing Init hooks`);
  for (const [name, hook] of Object.entries(initHooks)) {
    try {
      logger.info(`Import ${name}`);
      await hook.run();
    } catch (err) {
      logger.error(`Hook ${name} couldn't be executed`);
      logger.error(err);
    }
  }
};

As I didn't come up with the idea of using the import-modules library , is that good-pratice or could it be done in a better way using the possibilities of ES6?

PS: I already read the post import modules from all files in a directory .

CRoNiC
  • 329
  • 2
  • 4
  • 14
  • If you are talking pure, server-less, compile-free ES6 modules, no, its better you spend a little time generating index files that you can import. You could write a little script to generate those automatically for now, and in the future you could add to those to keep your library up to date. Otherwise, in pure browser-based ES6 this is not a solution you can even consider. It's file or bust, no such thing as a folder really. – somethinghere Aug 03 '23 at 12:50
  • Sorry I guess i didn't understand fully what you are trying to say. As I don't have to worry about a server and only rely on the functions beeing executed I guess I am serverless - am I? It is part of backend code so the second part "pure browser-based ES6" (do you mean for example the JS that comes with html pages?) shouldn't be the case. – CRoNiC Aug 03 '23 at 13:13
  • Well, if you are on a server you have a couple more options, but pure module wise all it is doing is basically generating them for you based on paths. It would still technically still be better to just create the index files yourself, as it means no 'implied' imports with potentially undefined behaviour. I think nodejs will automatically read the index file, so you can ommit it, but otherwise, I personally wouldn't rely on an imported module to do some work that you only need to do once to be setup correctly. – somethinghere Aug 03 '23 at 13:57

0 Answers0