简体   繁体   中英

How do you dynamically module.export all files in a folder?

I'm trying to dynamically export modules. I'm close but can't figure out how to fix my syntax.

Hard coded:

// index.js inside folder 'models'
const { User } = require('./User');
const { Token } = require('./Token');
const { Session } = require('./Session');

module.exports = {
    User,
    Token,
    Session,
};

Dynamically coded (doesn't work):

// index.js inside folder 'models'
const fs = require('fs');
const path = require('path');

module.exports = () => {
    fs.readdirSync(__dirname).forEach((file) => {
        if (file === 'index.js') return false;
        const fullName = path.join(__dirname, file);
        
        if (file.toLowerCase().indexOf('.js')) {
            // I think this somehow needs to be destructured like 
            // `return {require(fullName)}` or 
            // `require(fullName)[fullName]` I think
            require(fullName);
        }
    });
};

Elsewhere in my code, I initialize it based on the folder name:

// server.js
require('./models')();

Your dynamic export will not work because you are not returning anything to the exported function.

Try this code as your dynamic model export file

// index.js inside folder 'models'
const fs = require('fs')
const path = require('path')

const models = {}

fs.readdirSync(__dirname)
  .filter(file => file !== 'index.js')
  .forEach(file => {
    const fullName = path.join(__dirname, file)

    if (file.toLowerCase().endsWith('.js')) {
      // Removes '.js' from the property name in 'models' object
      const [filename] = file.split('.')
      models[filename] = require(fullName)[filename]
    }
  })

module.exports = models

This approach no longer exports a function so your require in server.js should now look like this

// server.js
require('./models');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM