Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: can I access the object that contains imported modules?

I'd like to create an array of the modules I am importing into Main.js file. How might I access the object that contains the imported modules?

EDIT To further explain, I am importing multiple classes into a Main.js file containing a Main class. Each of these classes comes from their own individual file, giving me import statements like this:

import Header from './features/Header.js';
import ImageStrip from './features/ImageStrip.js';
import AreaChart from './features/AreaChart.js';
import Axes from './features/Axes.js';

Is there a JavaScript object that contains the modules that are imported, for example something like [ Header, ImageStrip, AreaChart, Axes ]? Or is it possible to create one?

like image 662
interwebjill Avatar asked Aug 02 '26 23:08

interwebjill


1 Answers

There is no data structure that is automatically populated with the imports of the current file. You will have to construct your own array or object that manually lists each import.

import Feature1 from './features/Feature1.js';
import Feature2 from './features/Feature2.js';
import {SubFeatureX} from './features/Feature3.js';

const imports = [Feature1, Feature2, {SubFeatureX}];
// or
const imports = {Feature1, Feature2, Feature3: {SubFeatureX}};

If you need to create this variable in every file and are worried about the effort of maintaining the lists manually, you could compile the project with Babel and could write a Babel plugin to add this variable for you at the top of each file.

like image 152
Rory O'Kane Avatar answered Aug 05 '26 12:08

Rory O'Kane



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!