将模块的多个命名导出导入单个对象

时间:2019-03-14 17:32:32

标签: javascript import es6-modules

假设我有

animals.js

import cat from './cat';
import dog from './dog';
import emu from './emu';
import pig from './pig';
import cow from './cow';

export { cat, dog, emu, pig, cow };

在使用animals.js的模块中,如何仅将几个需要的对象导入键对象?我希望能够执行以下操作:

my-module.js

import { cat, dog } as housePets from './animals';

// housePets == { cat: theCatModule, dog: theDogModule }

有没有办法做到这一点?还是最好的方法是简单地分别导入所有这些对象,然后再构造自己的对象?

3 个答案:

答案 0 :(得分:4)

ECMA-262规范中,类似的事情是不可能的。他们只列出了这些possibilities

      case 'a':
      case 'A:
              type = "Milk A";
              h = 10;
              break;
      ...

您能做的最好的事情(仅添加一行)是:

import defaultExport from "module-name";
import * as name from "module-name";
import { export1 } from "module-name";
import { export1 as alias1 } from "module-name";
import { export1 , export2 } from "module-name";
import { foo , bar } from "module-name/path/to/specific/un-exported/file";
import { export1 , export2 as alias2 , [...] } from "module-name";
import defaultExport, { export1 [ , [...] ] } from "module-name";
import defaultExport, * as name from "module-name";
import "module-name";
var promise = import("module-name");

答案 1 :(得分:2)

如果您打算在其他模块中使用housePets,则还应将housePets导出为animals.js的一部分

animals.js

type Letter = "A" | "B"

type Useless = {}

type Container<T> =
    {
        type: "container"
        value: T
    }

type Input<T> = Useless | Container<T>

function transform<X extends Letter, Y extends Letter>(container: Input<X | Y>): asserts container is Container<X> {
    // custom logic
}

let container: Input<"A" | "B"> = undefined as any

// Asserts no B
transform<"A", "B">(container)

container // Container<"A" | "B">
          // Container<"A"> when Useless is commented
          // I want Container<"A">

my-module.js

import cat from './cat';
import dog from './dog';
import emu from './emu';
import pig from './pig';
import cow from './cow';

const housePets = { cat, dog }

export { cat, dog, emu, pig, cow };
export { housePets };

答案 2 :(得分:0)

@johannchopin在其答案中所述,根据最新规范,这是不可能的。但是,如果要使用单个键名导入文件中的所有导出,则可以尝试执行以下操作-

foo.js

const a = '123';
const b = 123;

export default { a, b };

bar.js

import KeyName from './temp';

console.log(KeyName.a, KeyName.b);