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
365 views
in Technique[技术] by (71.8m points)

javascript - ES6: Conditional & Dynamic Import Statements

Conditional

Is it possible to have conditional import statements like below?

if (foo === bar) {
    import Baz from './Baz';
}

I have tried the above but get the following error (from Babel) when compiling.

'import' and 'export' may only appear at the top level

Dynamic

Is it possible to have dynamic import statements like below?

for (let foo in bar) {
    if (bar.hasOwnProperty(foo)) {
        import Baz from `./${foo}`;
    }
}

The above receives the same error from Babel whilst compiling.

Is this possible to do or is there something I am missing?

Reasoning

The reason I am trying to do this is that I have a lot of imports for a number of "pages" and they follow a similar pattern. I would like to clean up my code base by importing these files with a dynamic for loop.

If this is not possible then is there a better way to handle large number of imports in ES6?

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

We do have dynamic imports proposal now with ECMA. This is in stage 2. This is also available as babel-preset.

Following is way to do conditional rendering as per your case.

if (foo === bar) {
    import('./Baz')
    .then((Baz) => {
       console.log(Baz.Baz);
    });
}

This basically returns a promise. Resolution of promise is expected to have the module. The proposal also has things like multiple dynamic imports, default imports, js file import etc. You can find more information about dynamic imports here.


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

...