ES6动态引用导入



假设我要导入几个具有相同方法的对象。如何动态地引用它们,比如通过字符串。

例如,

import { Foo } from 'path/to/foo';
import { Bar } from 'path/to/bar';
import { Baz } from 'path/to/baz';
const things = ['Foo', 'Bar', 'Baz'];
things.forEach(thing => {
thing.doSomething();
});

如果必须是字符串,你可以这样做:

import { Foo } from 'path/to/foo';
import { Bar } from 'path/to/bar';
import { Baz } from 'path/to/baz';
const things = {
'Foo': Foo, 'Bar': Bar, 'Baz': Baz
};
Object.keys(things).forEach(key => {
things[key].doSomething();
});

如果不必是字符串,您可以简单地创建一个导入对象数组

import { Foo } from 'path/to/foo';
import { Bar } from 'path/to/bar';
import { Baz } from 'path/to/baz';
const things = [Foo, Bar, Baz];
things.forEach(thing => {
thing.doSomething();
});

只是不要使用字符串,像这样使用你导入的:

import { Foo } from 'path/to/foo';
import { Bar } from 'path/to/bar';
import { Baz } from 'path/to/baz';
const things = [Foo, Bar, Baz];
things.forEach(thing => {
thing.doSomething();
});

最新更新