0

I have create react app code base in which i would like to be able to iterate over a nested structure of data to import one specific file.

I have the following structure:

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

In root.js I would like to go over every module in modules to import index.js so that the initialization data will be run at the start of the application. Its unclear to me what is the best way to do this preferably without using any plugins if there is a solution.

user3139545
  • 6,882
  • 13
  • 44
  • 87

2 Answers2

0

In my opinion, you should include them "manually"

// root.js

require('mod1.index')
require('mod2.index')

// ...

It's more clear and direct. Unless you have 100+ modules

EDIT for dynamic import:

No dependancies proposal (variation of 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))

One dependacie proposal: Get all files recursively in directories NodejS

Andrea Franchini
  • 548
  • 4
  • 14
0

Turns out this was simple:

Export everything in a modules.js files.

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

Then import the modules.js file in some root.js file.

user3139545
  • 6,882
  • 13
  • 44
  • 87