Pass options to ES6 module imports

Fabrizio Giordano picture Fabrizio Giordano · Apr 28, 2015 · Viewed 53.7k times · Source

Is it possible to pass options to ES6 imports?

How do you translate this:

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

to ES6?

Answer

Bergi picture Bergi · Apr 28, 2015

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.