Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerating wildcard imports in ES2015

So, in ES2015 you can have:

// Module A
export const FOO = 0;
export const BAR = 1;

// Module B
import * as AExports from 'ModuleA';
console.log(AExports.FOO); // Prints 0

What's the official way to enumerate the exports of ModuleA at runtime?

import * as AExports from 'ModuleA';
// Are these values guaranteed to be something?
Object.keys(AExports); // If so, should I look at enumerable values?
[...AExports]; // Iterable values?
Object.getOwnPropertyNames(AExports); // Here?

As far as I can tell, the spec describes this as an ImportedBinding but I can't deduce anything more from that.

NameSpaceImport : * as ImportedBinding
Let localName be the StringValue of ImportedBinding.
Let entry be the Record {[[ModuleRequest]]: module, [[ImportName]]: "*", [[LocalName]]: localName }.
Return a new List containing entry.
like image 790
AnilRedshift Avatar asked Jul 30 '16 22:07

AnilRedshift


People also ask

Why should we avoid wildcard imports?

4.1. Wildcard imports help us avoid a long list of imports in our code. Therefore, this impacts the readability of code as the reader may have to scroll a lot in every source code file before reaching the code that shows the logic.

How do you add wildcard imports to a class?

The solution is to go to Preferences ( ⌘ + , on macOS / Ctrl + Alt + S on Windows and Linux) > Editor > Code Style > Java > Imports tab set Class count to use import with '*' and Names count to use static import with '*' to a higher value. Any value over 99 seems to work fine.

Do wildcard imports affect performance?

There's no performance impact to using the wildcard since the compiler will only import the classes required by your code.

How do I disable wildcard import in Intellij?

Disable wildcard importsIn the Settings/Preferences dialog ( Ctrl+Alt+S ), select Editor | Code Style | Java | Imports. Make sure that the Use single class import option is enabled.


1 Answers

The important part of the spec in this case is that when you do

import * as foo from 'foo';

The foo variable's value is created at section 15.2.1.16.4 step 12.b which creates a Module Namespace Exotic Object, where properties are the named exports and all properties are enumerable so you are totally safe in using Object.keys(foo) to get the names of all of the named exports. The object is not iterable, so you will not be able to use an iterable spread, though you could use the proposed object spread syntax to copy the properties if you wanted. Object.getOwnPropertyNames should work fine too.

like image 127
loganfsmyth Avatar answered Nov 04 '22 09:11

loganfsmyth