I have an index file with multiple re-exports
// things/index.js
export { a } from 'a'
export { b } from 'b'
export { c } from 'c'
Now I want to use all the things in another file as arguments to my function.
This actually works:
import * as things from './things'
things[Symbol.iterator] = function* () {
for (let v in this) { yield v }
}
function print(things) {
[...things].forEach(thing => {
console.debug('thing', thing)
});
}
print(things)
// prints:
// thing a
// thing b
// thing c
I would like to avoid having to set an iterator this way and instead export it together with the things . Is there a way?
Rather than using separate named exports, consider having a single export (named or otherwise), which is an object with a
, b
, c
properties, and has a Symbol.iterator
property:
// things/index.js
import { a } from 'a'
import { b } from 'b'
import { c } from 'c'
export const things = {
a,
b,
c,
[Symbol.iterator]: function* () {
yield a;
yield b;
yield c;
}
};
Or iterate over the values (the Symbol.iterator
property won't be included while iterating, since it's not enumerable):
// things/index.js
import { a } from 'a'
import { b } from 'b'
import { c } from 'c'
export const things = {
a,
b,
c,
[Symbol.iterator]: function* () {
yield* Object.values(this);
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.