Pass options to ES6 module imports Ask Question

Pass options to ES6 module imports Ask Question

Is it possible to pass options to ES6 imports?

How do you translate this:

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

to ES6?

ベストアンサー1

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.default(someoptions));

or

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

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

おすすめ記事