Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard or asterisk (*) vs named or selective import es6 javascript

Just wondering which one is the best way to use import:

import * as Foo from './foo';

VS:

import { bar, bar2, bar3 } from './foo';

In terms of efficiency, say for example, I'm using webpack for bundling all the JavaScript files. Will the first one actually importing everything even though I'm not using them in the main code?

Some references that I can find are:

In Airbnb style guide, they are recommending no wildcard so there will always be default import object, and this.

like image 397
andiwin Avatar asked Feb 05 '17 11:02

andiwin


People also ask

What is wildcard import in Javascript?

With wildcards imports, an _interopRequireWildcard function is defined and used to assign all exports to the namespace variable. It's worth noting that compiled code will only contain a single _interopRequireWildcard definition, and one call to require and _interopRequireWildcard for each import.

What is import * as in JS?

The import * as name syntax imports all exported content of a javascript file.


1 Answers

If you use webpack with the dead code elimination provided by the new uglify, or rollupjs with tree-shaking, then the unused imports will be stripped.

I partially agree with the airbnb styleguide to not to use wildcard imports, although javascripts wildcard imports do not suffer from the same diseases as for example pythons or javas wildcard imports, namely it does not pollute the scope with variable names defined in other modules (you can only access them by moduleB.foo, not foo when using import * as moduleB from ...).

About the article on testing: I kindof understand the concerns, but I see nothing that cannot be solved there. You can mock the imports themselves with some custom module loader (a custom amd module loader is literally 15 lines of code), so you dont have to mess with the local scope of the tested module.

like image 196
Tamas Hegedus Avatar answered Oct 05 '22 12:10

Tamas Hegedus