How to import/export a module based on browser compatibility

Viewed 146

I'm trying to import a module only for IE11, https://react-hook-form.com/faqs/, and then re-import it in another file.

// utils/index.js
let loadModule;

if (isIE11) {
    loadModule = require('react-hook-form/dist/index.ie11');
} else {
    loadModule = require('react-hook-form');
}

module.exports = { ...loadModule };

// import it in another file

import {useForm} from './utils/index';
...

The question would be if this is possible to do it with import/export, and if my code would be the proper way to handle this case

1 Answers

The question would be if this is possible to do it with import/export, and if my code would be the proper way to handle this case

Not import/export declarations, no. But it's possible with dynamic import (import(), part of ES2020) and top-level await (currently Stage 3, but likely to advance very soon and be in ES2021).

utils/index.js:

const { useForm } = await import(
    isIE11
        ? 'react-hook-form/dist/index.ie11'
        : 'react-hook-form'
);

export { useForm };

Another file:

import { useForm } from './utils/index';

Both are well-supported in modern bundlers, and since you're dealing with IE11, you must be dealing with bundlers if you're using JavaScript modules rather than require.

Related