Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

javascript - ES6: import many files

I have a script that imports a lot of AMD modules and calls an initialization method on each one:

define(['underscore', './mod0', ..., './modN'], function (_) {
    _.each(_.toArray(arguments).slice(1), function (m) {
        init(m);
    });
});

I need to switch to ES6 import syntax and I am trying to figure out if it is possible to import modules from a list, in a manner similar to my AMD code. I want to avoid insanity like:

import mod0 from './mod0';
...
import modN from './modN';

init(mod0);
...
init(modN);

Any advice on how this can be accomplished? thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Is it possible to import modules from a list?

No, not without explicitly invoking your module loader (whichever that is). There is no way to do this using import declarations.

Any advice on how this can be accomplished?

eval could probably do it :-)

I would recommend using two modules:

// index.js
export mod0 from './mod0';
…
export modN from './modN';

// init-all.js
import * as modules from './index'; // enumerable namespace

for (var moduleIdentifier in modules)
    init(modules[moduleIdentifier]);

You could potentially do the same with only a single module (that imports itself as a module namespace object), but that surely would be real insanity.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...