5

Supposed, we have some modules imported by the current module:

import {A1, A2, A3} from "./ModuleA";
import {B1, B2, B3} from "./ModuleB";
import {C1, C2, C3} from "./ModuleC";

function getTheListOfImportedModules() {
// This should return something similar to ["./ModuleA", "./ModuleB", "./ModuleC"]
}

Is there a way to get the list of all the imported modules at runtime without having to manually list each modules during editing? On the side, if that is possible then is it possible to also get the list of imported objects from these modules: [A1, A2, A3, B1, B2, B3, C1, C2, C3] at runtime?

jmrk
  • 34,271
  • 7
  • 59
  • 74
user3330840
  • 6,143
  • 7
  • 26
  • 39
  • Does this answer your question? [JavaScript: can I access the object that contains imported modules?](https://stackoverflow.com/questions/49885861/javascript-can-i-access-the-object-that-contains-imported-modules) – jmrk Jul 12 '20 at 12:30
  • There's also this: https://stackoverflow.com/questions/9791925/list-of-currently-loaded-node-js-modules – jmrk Jul 12 '20 at 12:31
  • @jmrk From those posts, it seems it is not possible in the browser. Any information on whether it is possible using browser specific implementations? – user3330840 Jul 14 '20 at 16:16
  • As you said: From those posts, it seems it is not possible in the browser. – jmrk Jul 15 '20 at 09:27

1 Answers1

0

This should work as long as node.js is involved:

import {useState, useEffect} from 'react';

import CSS from './Popup.module.css';
import Confetti from '../../elements/confetti/Confetti';
import Graphic from '../../elements/graphic/Graphic';
import {arrayShuffle} from '../../../utility/tools';

const moduleNames: string[] = [];
for (const path of module.children as unknown as string[]) {
  // Skipping libraries
  if (!path.includes('node_module')) {
    const moduleName = path
      .split('/')
      .pop()
      ?.match(/(.*).[jt]sx?/i)
      ?.pop();

    if (moduleName) {
      moduleNames.push(moduleName);
    }
  }
}

console.log(moduleNames); // ["Confetti", "Graphic", "tools"]
Saber Hayati
  • 688
  • 12
  • 14
  • Sure, please feel free to update the answer when we have the Broser-side solution available, so that it can be marked as the answer. – user3330840 Jan 17 '23 at 04:40