Can I load multiple files with one require statement?

前端 未结 5 1350
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-13 13:31

maybe this question is a little silly, but is it possible to load multiple .js files with one require statement? like this:

var mylib = require(\'./lib/mylib         


        
5条回答
  •  悲&欢浪女
    2020-12-13 14:38

    I was doing something similar to what @freakish suggests in his answer with a project where I've a list of test scripts that are pulled into a Puppeteer + Jest testing setup. My test files follow the naming convention testname1.js - testnameN.js and I was able use a generator function to require N number of files from the particular directory with the approach below:

    const fs = require('fs');
    const path = require('path');
    
    module.exports = class FilesInDirectory {
    
        constructor(directory) {
    
            this.fid = fs.readdirSync(path.resolve(directory));
            this.requiredFiles = (this.fid.map((fileId) => {
                let resolvedPath = path.resolve(directory, fileId);
                return require(resolvedPath);
            })).filter(file => !!file);
    
        }
    
        printRetrievedFiles() {
            console.log(this.requiredFiles);
        }
    
        nextFileGenerator() {
    
            const parent = this;
            const fidLength = parent.requiredFiles.length;
    
            function* iterate(index) {
                while (index < fidLength) {
                    yield parent.requiredFiles[index++];
                }
            }
            return iterate(0);
        }
    
    }
    

    Then use like so:

    //Use in test
    const FilesInDirectory = require('./utilities/getfilesindirectory');
    const StepsCollection = new FilesInDirectory('./test-steps');
    const StepsGenerator = StepsCollection.nextFileGenerator();
    
    //Assuming we're in an async function
    await StepsGenerator.next().value.FUNCTION_REQUIRED_FROM_FILE(someArg);
    

提交回复
热议问题