简体   繁体   中英

Export all files from a folder in es module

I have the following script which is attempted at exporting every single file from a particular folder, but I'm stucked at the export part of it.

Below is what I've attempted:

index.js

function exportAllFiles() {
    fs.readdir(filesDir, (err, files) => {
        if (err) {
            console.log(err);
            return;
        }
        files.forEach(async file => {
            const module = await import(file);
            //'export module.default' ;export statement is not working for me here, how can I make it work here?
        });
    })
}

exportAllFiles();

After importing each file as seen above I have no idea how to export it as the export statement doesn't seem to work for me in that block.

Any ideas would be really appreciated.

Thanks

If you put this code into "index.js" then it'll pick up any other JS modules in that directory and expose them as sub-modules.

var fs = require('fs');

fs.readdirSync('./dir/path').forEach(function(file){
    if ( file.indexOf(".js") > -1 && file != "index.js" ) 
        exports[ file.replace('.js','') ] = require('./'+file);
});

Be sure to replace ./dir/path with the path of the directory.

Source

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