For the current module, get the list of all directly imported modules at runtime (Javascript/Typescript)

Viewed 799

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?

1 Answers

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"]
Related