简体   繁体   English

JavaScript:我可以访问包含导入模块的对象吗?

[英]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. 我想创建一个要导入Main.js文件的模块数组。 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. 编辑为了进一步说明,我将多个类导入包含Main类的Main.js文件中。 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 ] ? 是否有一个JavaScript对象包含导入的模块,例如[ Header, ImageStrip, AreaChart, Axes ] Or is it possible to create one? 还是可以创建一个?

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. 如果您需要在每个文件中创建此变量,并且担心手动维护列表的工作量,则可以使用Babel编译项目,并可以编写Babel插件在每个文件的顶部为您添加此变量。

file.js
export firstFunc() {}
export nextFunc() {}
newFile.js
import * as Obj from "./file.js";

Does it make sense? 是否有意义?

import {firstMethod, secondMethod} from "./firstFile";
import {anotherFirstMethod} from "./secondFile";

export {
    firstMethod,
    secondMethod,
    anotherFirstMethod
};

or 要么

import * as Obj from "./firstFile";
import * as Obj2 from "./secondFile";

export {
    Obj,
    Obj2
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM