简体   繁体   English

如何基于浏览器兼容性导入/导出模块

[英]How to import/export a module based on browser compatibility

I'm trying to import a module only for IE11, https://react-hook-form.com/faqs/ , and then re-import it in another file.我正在尝试为 IE11 导入一个模块, https: //react-hook-form.com/faqs/,然后在另一个文件中重新导入它。

// 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问题是这是否可以通过导入/导出来实现,以及我的代码是否是处理这种情况的正确方法

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现在的问题是,如果这是可能做到这一点的import / export ,如果我的代码将处理这种情况的正确方法

Not import / export declarations , no.import / export报关,没有。 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).但是使用动态导入import() ,ES2020 的一部分)和顶级await (目前是第 3 阶段,但可能很快会推进并进入 ES2021)是可能的。

utils/index.js : 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 .两者都在现代捆绑器中得到了很好的支持,并且由于您正在处理 IE11,如果您使用的是 JavaScript 模块而不是require ,那么您必须处理捆绑器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM