简体   繁体   English

从 es 模块中的文件夹导出所有文件

[英]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索引.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.如果您将此代码放入“index.js”,那么它会选择该目录中的任何其他 JS 模块并将它们作为子模块公开。

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.请务必将./dir/path替换为目录的path

Source 资源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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