Pass options to ES6 module imports

后端 未结 7 1404
[愿得一人]
[愿得一人] 2020-11-22 04:43

Is it possible to pass options to ES6 imports?

How do you translate this:

var x = require(\'module\')(someoptions);

to ES6?

7条回答
  •  面向向阳花
    2020-11-22 05:23

    There is no way to do this with a single import statement, it does not allow for invocations.

    So you wouldn't call it directly, but you can basically do just the same what commonjs does with default exports:

    // module.js
    export default function(options) {
        return {
            // actual module
        }
    }
    
    // main.js
    import m from 'module';
    var x = m(someoptions);
    

    Alternatively, if you use a module loader that supports monadic promises, you might be able to do something like

    System.import('module').ap(someoptions).then(function(x) {
        …
    });
    

    With the new import operator it might become

    const promise = import('module').then(m => m(someoptions));
    

    or

    const x = (await import('module'))(someoptions)
    

    however you probably don't want a dynamic import but a static one.

提交回复
热议问题