如何有条件导入ES6模块?

我需要做类似的事情:


if (condition) {

    import something from 'something';

}

// ...

if (something) {

    something.doStuff();

}

上面的代码无法编译;它抛出SyntaxError: ... 'import' and 'export' may only appear at the top level。


我尝试使用此处System.import所示的方法,但是我不知道从哪里来。是ES6提案最终没有被接受吗?该文章中指向“编程API”的链接将我转至不推荐使用的docs页面。System


哈士奇WWW
浏览 1174回答 3
3回答

DIEA

现在,ECMA确实有动态进口建议。这是在第3阶段。这也可以作为babel-preset使用。以下是根据您的情况进行条件渲染的方法。if (condition) {    import('something')    .then((something) => {       console.log(something.something);    });}这基本上返回了一个承诺。承诺解决方案有望包含该模块。该提案还具有其他功能,例如多个动态导入,默认导入,js文件导入等。您可以在此处找到有关动态导入的更多信息。

富国沪深

如果需要,可以使用require。这是有条件的require语句的一种方式。let something = null;let other = null;if (condition) {    something = require('something');    other = require('something').other;}if (something && other) {    something.doStuff();    other.doOtherStuff();}

烙印99

您不能有条件地导入,但是可以做相反的事情:有条件地导出某些内容。这取决于您的用例,因此此解决方法可能不适合您。你可以做:api.jsimport mockAPI from './mockAPI'import realAPI from './realAPI'const exportedAPI = shouldUseMock ? mockAPI : realAPIexport default exportedAPIapiConsumer.jsimport API from './api'...我用它来模拟诸如mixpanel等的分析库,因为我目前无法拥有多个版本或前端。不是最优雅的,但有效。根据环境的不同,我在这里和那里只有几个“ if”,因为在混合面板的情况下,它需要初始化。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript