Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import multiple named exports of module into a single object

Suppose I have:

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 };

In a module that uses animals.js, how can I import only a couple of needed ones into a keyed object? I'd like to be able to do something like:

my-module.js

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

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

But according to my IDE, this syntax is not correct.

Is there a way to do this? Or is the best way to simply import all of them individually, then construct my own objects afterward?

like image 689
MegaMatt Avatar asked Mar 14 '19 17:03

MegaMatt


2 Answers

As @johannchopin mentioned in their answer, this is not possible as per the latest specs. However if you want import ALL the exports from a file in a single key name, you can try something like this -

foo.js

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

export default { a, b };

bar.js

import KeyName from './temp';

console.log(KeyName.a, KeyName.b);
like image 150
potatoxchip Avatar answered Oct 11 '22 18:10

potatoxchip


Sadly nothing like that is possible in the ECMA-262 specifications. They only lists these possibilities:

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");

Best that you can do (only add a single line) is that:

import { cat, dog } from './animals';
const housePets = { cat, dog };
like image 26
johannchopin Avatar answered Oct 11 '22 20:10

johannchopin