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

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


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.


Concerning this part of the question :

Will the first one actually importing everything even though I'm not using them in the main code?

Here's how it gets compiled with Babel 6.26:

Named

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

... becomes ...

'use strict';var _foo = require('./foo');

Wildcard

import * as Foo from './foo';

... becomes ...

'use strict';var _foo = require('./foo');var Foo = _interopRequireWildcard(_foo);function _interopRequireWildcard(obj) {     if (obj && obj.__esModule) {         return obj;    } else {        var newObj = {};         if (obj != null) {             for (var key in obj) {                 if (Object.prototype.hasOwnProperty.call(obj, key))                    newObj[key] = obj[key];            }        }        newObj.default = obj;         return newObj;    }}

In both cases the whole file is imported through require.

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.

Ultimately, the use of wildcard imports will involve a bit more processing at run-time and cause a slight increase in size for the compiled js.


Since, with a modern WebPack setup, the two will generate the same compiled/transpiled JS, the real value in named imports is how much more expressive it is. By naming your imports you are telling any one that opens the file which functions from a module you are going to use. An example of where this can be helpful is when writing tests, if mocking is necessary, you have an explicit list of imports to mock.