我需要做一些类似的事情:

if (condition) {
    import something from 'something';
}
// ...
if (something) {
    something.doStuff();
}

上面的代码不能编译;它抛出SyntaxError:…“import”和“export”只能出现在顶层。

我尝试使用系统。导入如下所示,但我不知道系统来自哪里。是ES6提案最终没有被接受吗?那篇文章中的“程序化API”链接把我扔到了一个废弃的文档页面。


当前回答

Require()是一种在运行时导入某些模块的方法,如果与字符串文本路径一起使用,它同样有资格进行静态分析。这是捆绑器为捆绑包选择依赖项所必需的。

const defaultOne = require('path/to/component').default;
const NamedOne = require('path/to/component').theName;

对于具有完整静态分析支持的动态模块解析,首先在索引器(index.js)中索引模块,然后在主机模块中导入索引器。

// index.js
export { default as ModuleOne } from 'path/to/module/one';
export { default as ModuleTwo } from 'path/to/module/two';
export { SomeNamedModule } from 'path/to/named/module';

// host.js
import * as indexer from 'index';
const moduleName = 'ModuleOne';
const Module = require(indexer[moduleName]);

其他回答

我知道这不是问题所要求的,但下面是我在使用vite时使用模拟的方法。我相信我们也可以在webpack和其他产品上做到这一点。

假设我们有两个具有相同接口的库:link.js和link-mock.js,那么:

在我的vite.config.js中

export default defineConfig(({ command, mode }) => {
    
    const cfg = {/* ... */}

    if (process.env.VITE_MOCK == 1) {
        cfg.resolve.alias["./link"] = "./link-mock"; // magic is here!
    }

    return cfg;
}

代码:

import { link } from "./link";

在控制台,我们称之为:

# to use the real link.js
npm run vite

# to use the mock link-mock.js
VITE_MOCK=1 npm run vite

or

包中。json脚本

{
    ....
    "scripts": {
        "dev": "vite",        
        "dev-mock": "VITE_MOCK=1 vite"
    }
}

看起来答案是,就目前而言,你不能。

http://exploringjs.com/es6/ch_modules.html#sec_module-loader-api

我认为其目的是尽可能地支持静态分析,而有条件地导入模块则打破了这一点。另外值得一提的是——我使用的是Babel,我猜Babel不支持System,因为模块加载器API没有成为ES6标准。

如果你愿意,你可以使用require。这是一种使用条件require语句的方法。

let something = null;
let other = null;

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

不,你不能!

然而,遇到这个问题应该让你重新思考如何组织代码。

在ES6模块之前,我们有使用require()语法的CommonJS模块。这些模块是“动态的”,这意味着我们可以根据代码中的条件导入新模块。-来源:https://bitsofco.de/what-is-tree-shaking/

我猜他们在ES6上放弃支持的原因之一是编译它非常困难或不可能。

你不能有条件地进口,但你可以做相反的事情:有条件地出口。这取决于您的用例,所以这种方法可能不适合您。

你可以:

api.js

import mockAPI from './mockAPI'
import realAPI from './realAPI'

const exportedAPI = shouldUseMock ? mockAPI : realAPI
export default exportedAPI

apiConsumer.js

import API from './api'
...

我用它来模拟分析库,如mixpanel等…因为我目前不能有多个构建或我们的前端。不是最优雅的,但很管用。我只是在这里和那里有几个“if”,这取决于环境,因为在mixpanel的情况下,它需要初始化。