Is it possible to import modules from all files in a directory, using a wildcard?

前端 未结 13 2037
陌清茗
陌清茗 2020-11-22 04:25

With ES6, I can import several exports from a file like this:

import {ThingA, ThingB, ThingC} from \'lib/things\';

However, I like the orga

相关标签:
13条回答
  • 2020-11-22 05:00

    You can use require as well:

    const moduleHolder = []
    
    function loadModules(path) {
      let stat = fs.lstatSync(path)
      if (stat.isDirectory()) {
        // we have a directory: do a tree walk
        const files = fs.readdirSync(path)
        let f,
          l = files.length
        for (var i = 0; i < l; i++) {
          f = pathModule.join(path, files[i])
          loadModules(f)
        }
      } else {
        // we have a file: load it
        var controller = require(path)
        moduleHolder.push(controller)
      }
    }
    

    Then use your moduleHolder with dynamically loaded controllers:

      loadModules(DIR) 
      for (const controller of moduleHolder) {
        controller(app, db)
      }
    
    0 讨论(0)
提交回复
热议问题