How can I conditionally import an ES6 module? How can I conditionally import an ES6 module? javascript javascript

How can I conditionally import an ES6 module?


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

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

if (condition) {    import('something')    .then((something) => {       console.log(something.something);    });}

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


If you'd like, you could use require. This is a way to have a conditional require statement.

let something = null;let other = null;if (condition) {    something = require('something');    other = require('something').other;}if (something && other) {    something.doStuff();    other.doOtherStuff();}


You can't import conditionally, but you can do the opposite: export something conditionally. It depends on your use case, so this work around might not be for you.

You can do:

api.js

import mockAPI from './mockAPI'import realAPI from './realAPI'const exportedAPI = shouldUseMock ? mockAPI : realAPIexport default exportedAPI

apiConsumer.js

import API from './api'...

I use that to mock analytics libs like mixpanel, etc... because I can't have multiple builds or our frontend currently. Not the most elegant, but works. I just have a few 'if' here and there depending on the environment because in the case of mixpanel, it needs initialization.