pixelwiz pixelwiz - 30 days ago 9
Javascript Question

Syntax for importing functions from modules in ES6

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 R = require('ramda');

Option 1 is to import certain functions:

import { cond, T, always, curry, compose } from 'ramda';

Option 2 is to import the whole module like:

import * as R from "ramda";

I would prefer to reference the module from which the function is being called like so:


But if the 2nd option is used, does it bring in every Ramda function not just the ones used in a module I'm working in? Are there any impacts on actual memory use, or bandwidth use as far as what gets sent to the browser if option 2 is used?
Is it possible to somehow do this:

// invalid syntax below:
import R { cond, T, always, curry, compose } from 'ramda';

My question is kinda related to this one, but it's a bit different
import R (ramda) into typescript .ts file

Answer Source

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.