【问题标题】:Iterate over folder and import index.js遍历文件夹并导入 index.js
【发布时间】:2020-01-27 17:59:16
【问题描述】:

我已经创建了 react 应用程序代码库,我希望能够在其中迭代数据的嵌套结构以导入一个特定文件。

我有以下结构:

root.js
-modules
-- mod1
--- index.js 
-- mod2
--- index.js 

root.js 中,我想检查模块中的每个模块以导入index.js,以便在应用程序启动时运行初始化数据。我不清楚如果有解决方案,最好不使用任何插件来做到这一点的最佳方法是什么。

【问题讨论】:

    标签: javascript node.js reactjs create-react-app


    【解决方案1】:

    在我看来,您应该“手动”包含它们

    // root.js
    
    require('mod1.index')
    require('mod2.index')
    
    // ...
    

    更清晰直接。除非你有 100 多个模块

    动态导入编辑:

    无依赖提案(https://gist.github.com/kethinov/6658166#gistcomment-1603591 的变体)

    'use strict'
    
    const fs = require('fs')
    
    const walkSync = function (dir, filelist) {
      const files = fs.readdirSync(dir)
      filelist = filelist || []
      files.forEach(function (file) {
        if (fs.statSync(dir + '/' + file).isDirectory()) {
          filelist = walkSync(dir + '/' + file, filelist)
        } else {
          filelist.push(dir + '/' + file)
        }
      })
      return filelist
    }
    
    allFiles = walkSync('./src')
    
    allFiles.filter(f => f.split('/').pop() == 'index.js').forEach(f => require(f))
    

    一个依赖提案:Get all files recursively in directories NodejS

    【讨论】:

    • 这不是一个选项。
    • 您是否考虑过使用非本地模块来扫描文件夹?或者您更喜欢不添加其他依赖项?
    • 好吧,任何开始的解决方案都可以。但我宁愿没有依赖。
    【解决方案2】:

    原来这很简单:

    导出modules.js 文件中的所有内容。

    const req = require.context('./', true, /^\.\/[a-zA-Z0-9]+\/index.js$/);
    const modules = req.keys().map(req);
    module.exports = modules;
    

    然后将modules.js文件导入某个root.js文件中。

    【讨论】:

      猜你喜欢
      • 2019-04-22
      • 2018-02-11
      • 1970-01-01
      • 2016-05-28
      • 1970-01-01
      • 2022-10-24
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      相关资源
      最近更新 更多