📖
Internal Wiki
  • My Knowledge Wiki 🌿
  • ai
    • Prompts
  • beautiful
    • Beautiful websites
  • blog
    • best blog times
    • Good Blog Posts
  • career
    • First 90 Days
    • income streams
    • interview questions
    • Misc
    • Negotiation
    • On Call
  • coding
    • AWS
    • Bash
    • Browser Extensions
    • Cloudflare
    • CopyQ
    • Docker
    • Express
    • Filebase
    • Firebase
    • Git Commit Message Standards
    • GIT
    • Github Actions
    • html
    • TypeScript / JavaScript
    • JavaScript / TypeScript
    • NodeJS
    • npm
    • npx
    • Service Workers
    • Tunnel
    • Vite
    • Wrangler
    • New Angular Project
    • snippets
      • angular
        • Performance Tracking
        • Web3 in Angular Projects
      • nodejs
        • Dynamically load classes
  • communities
    • Communities
  • devex
    • Browser Experience
  • github
    • CI/CD
  • infra
    • Kubernetes
    • Windows
  • links
    • AI
    • Awesome lists
    • Beautify Code
    • cli
    • Code Snippet Images
    • Coding
    • Courses
    • Creators
    • Crypto
    • CSS
    • Design
    • Diagrams
    • Domains
    • events
    • Fonts
    • Funding
    • gifs
    • Github
    • I18N
    • Icons
    • Identity
    • Image (drawing, manipulation, ...)
    • All around infra (hosting, serverless, ...)
    • JSON utils
    • Libraries and Tools
    • Markdown
    • Machine Learning
    • Monetization
    • Music
    • No Code Tools
    • Node and NPM (and other package managers)
    • nostr
    • Other
    • Pitch
    • react
    • Resources
    • Resumes
    • SaaS
    • scraping
    • Screenshots
    • Search
    • SEO
    • Services
    • Social Media Engagement
    • Popular Stacks
    • Storage
    • Terms
    • Text to speech
    • Text Effects
    • Tutorials
    • video
    • Nice wasm libs
    • Writing
    • YouTube
  • linux-commands
    • convert
    • ffmpeg
    • General
    • Screen
  • Quotes
    • Twitter Quotes
  • reddit
    • Side projects
  • shops
    • Dog Stuff
    • wir-machen-druck
  • watch
    • Youtube Videos
  • wine
    • Wine
  • learning
    • house
      • Heating Energy Act
    • sbf
      • SBF Navi
      • SBF Praxis
      • SBF
Powered by GitBook
On this page
  • Interface
  • Classes to be imported
  • Loader
  1. coding
  2. snippets
  3. nodejs

Dynamically load classes

Use case: extend functionality by just adding a new file into a folder.

Interface

To be type safe it's recommended to implement an interface:

export interface MyInterface {
  some_function: (input: MyType) => void;
  another_function: (input: MyType2) => string;
}

Classes to be imported

// myClass.ts
export default class MyClass implements MyInterface {
  async some_function(input: MyType) {
    // ...
  }

  another_function(input: MyType2) {
    // ...
  }
}

Loader

import logger from "./Logger";
import * as fs from "fs";
import * as path from "path";
import { MyInterface } from "./MyInterface";

const MODULE_DIR_NAME = "modules";
const MODULE_DIR = path.join(__dirname, "..", MODULE_DIR_NAME);

export class MyLoader {
  public static async loadModules(): Promise<MyInterface[]> {
    logger.info(`MyLoader | Loading Classes`);
    const classes: MyInterface[] = [];
    const files = fs.readdirSync(MODULE_DIR);
    for (const file of files) {
      const moduleName = file.split(".")[0];
      logger.info(`MyLoader | Loading class <${file}>`);
      const Module = await import(`${MODULE_DIR}/${moduleName}`);
      try {
        const instanceOfModule = new Module.default();
        if (
          "some_function" in instanceOfModule &&
          "another_function" in instanceOfModule
        ) {
          logger.info(`MyLoader | Successfully loaded <${file}>`);
          classes.push(new Module.default());
        } else {
          logger.error(
            `MyLoader | Class <${file}> does not implement interface <MyInterface>. Ignoring class.`
          );
        }
      } catch (error) {
        logger.error(`MyLoader | Failed to load <${file}>`, { error });
      }
    }

    return classes;
  }
}
PreviousnodejsNextcommunities

Last updated 3 years ago