6

Suppose I have a module foo like this:

export const f = x => x + 1;

export const g = x => x * 2;

I can use this module like this:

import { f, g } from 'foo';

console.log(f(g(2)));

Or like this:

import * as foo from 'foo';

console.log(foo.f(foo.g(2)));

I prefer the second way because it prevents name collisions between modules.

However, is import * less efficient? Does it prevent bundlers (such as Rollup and Webpack) from spotting unused imports and removing them?

Sébastien
  • 11,860
  • 11
  • 58
  • 78
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245

4 Answers4

3

When you specify imports as import { f, g } from 'foo'; you guarantee better performance in terms of speed in compilation and bundle size as you will be getting only the dependencies you need.

Notes: as loganfsmyth pointed out, some recent compiler/bundle are able to reference what actually is being used only, this IMO is an additional step which could cost some compilation time (although I did not have time to benchmark this assumption).

GibboK
  • 71,848
  • 143
  • 435
  • 658
  • 1
    Most module bundlers are also able to look at the namespace object to see what references are actually used, so I don't think this is accurate? – loganfsmyth Mar 21 '18 at 22:29
  • 1
    Please do a benchmark. I'm certain the difference is not noticeable. – Bergi Mar 21 '18 at 22:49
  • @Bergi good point +1, I will also add that it depends my the number of exports and size of the project. – GibboK Mar 21 '18 at 22:56
1

import * is less efficient in that you are using more memory to pull the entire library as opposed to just the specific methods that you actually need

  • That depends entirely on the module implementation. Webpack is perfectly able to optimize the main cases of `import * as` too. – loganfsmyth Mar 21 '18 at 22:29
0

Webpack at least (not sure about Rollup), is perfectly able to see that foo.f is a reference to the f exported name, so your two examples will behave the same.

loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
0

For most bundlers this does not matter since everything has to be included, 'cause

export const g = (() => {
    console.log("Side effects!");

    return x => x * 2;
})();
H.B.
  • 166,899
  • 29
  • 327
  • 400