Is using an ES6 import to load specific names faster than importing a namespace?

后端 未结 2 2047
感动是毒
感动是毒 2020-11-27 20:53

I\'ve found at least two ways to import functions in from a module like Ramda for example. There are probably a few more ways to do something very similar like const

相关标签:
2条回答
  • 2020-11-27 21:35

    TL;DR: It does not matter.


    import * as … from 'ramda';
    import { … } from 'ramda';
    

    will both by default always bring in the complete Ramda module with all its dependencies. All code inside the module would be run, and which syntax was used to reference the exported bindings doesn't matter. Whether you use named or namespaced imports comes down to preference entirely.

    What can reduce the file size to download and the used memory is static analysis. After having evaluated the module, the engine can garbage-collect those bindings that are referenced from nowhere. Module namespace objects might make this slightly harder, as anyone with access to the object can access all exports. But still those objects are specified in a way (as immutable) to allow static analysis on their usage and if the only thing you're doing with them is property access with constant names, engines are expected to utilise this fact.

    Any size optimisation involves guessing which parts of the module need to be evaluated and which not, and happens in your module bundler (like Rollup or WebPack). This is known as Tree Shaking, dropping parts of the code and entire dependencies when not needed (used by anything that got imported). It should be able to detect which imports you are using regardless of the import style, although it might have to bail out when are doing unusual things with the namespace object (like looping it or using dynamic property access).

    To learn about the exact guesses your bundler can make, contact its documentation.

    0 讨论(0)
  • 2020-11-27 21:37

    @Bergi is right in his comment, which I think should be the answer. I would also like to point out you can always try things out in Babel to see what it compiles to: click here to see what an example destructuring actually does

    So basically even if you destructure just one function from the module, the whole module will be required. In the Babel example I gave, I just extracted Component from the 'react' module, but the compiled code actually just required the whole thing. :)

    0 讨论(0)
提交回复
热议问题