import and execute all files in a folder with es6

You can do this with dynamic imports:

import { promises as fs } from 'fs';
import { join } from 'path';

export default async function*() {
  for (const model of await fs.readdir(__dirname)) {
    if (model === "index.js") continue;
    yield await import(join(__dirname, model));
  }
}
import modelDefiners from "./models";

(async () => {
  for await (const {default: modelDefiner} of modelDefiners()) {
    if (typeof modelDefiner === "function") {
      modelDefiner();
    }
  }
})();

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top