6

How does one import map or merge or any other function from multiple imports?

import { map } from 'lodash';
import { map } from 'rxjs/operators';
import { map } from 'ramda';

The obvious answer is to:

import { map as _map } from 'lodash';
import { map as rxMap } from 'rxjs/operators';
import { map as RMap } from 'ramda';

But this is ugly and obscures code. I consider this a hack, not a solution, but a workaround due to the limitations of static analysis

I can think of another way:

import * as _ from 'lodash';
import { map } from 'rxjs/operators';
import * as R from 'ramda';

However, the JS community frowns upon this due to tree-shaking reasons. However, I am in the belief that it is over-exaggerated, only saving 45kb.

Dolan
  • 1,519
  • 4
  • 16
  • 36

3 Answers3

6

Basically you can create your own util bundles. For example:

// utils/lodash.js
export { map, get, set } from 'lodash';

// yourScript.js
import * as _ from 'utils/lodash';
Eugene Tsakh
  • 2,777
  • 2
  • 14
  • 27
0

If you're using those map features for specific use cases (observables, array/object manipulation, etc.) throughout your application, it is probably best to rename the methods to reflect your application's specific use case.

I'd treat them the same as if you had three non-vendor methods called "map". If you found this in your own code, you would determine if all the methods do the same thing, and if not, rename them to be more specific about what they do.

For example, rxjs.map would become mapObservable, etc. There would be a maintenance hit enforcing your new name across your modules, but the benefit would be that there is less context switching your developers will need to do to understand what's being used and why.

This may be a heavily subjective question, as the answer is likely going to vary by team, conventions, and your application.

P.S. One ways of reducing the maintenance would be to expose these methods through a wrapper, and have your team use this wrapper for those specific functions.

JohnsonCore
  • 544
  • 1
  • 4
  • 13
  • The wrapper idea I am starting to like. It sounds like @Eugene's idea – Dolan Oct 11 '18 at 23:59
  • The reason I do not like mapObservable, is that by that definition, the project should name their other rxjs methods mergeObservable, tapObservable, combineLatestObservable? Where do we draw the line? It is a lot of cognitive load, and will give us all a headache. – Dolan Oct 12 '18 at 00:02
  • I think you're right. Eugene's solution is elegant, and lets you get the best of both worlds. – JohnsonCore Oct 12 '18 at 00:13
0

It is honestly up to what you / whoever you're working for values more. Sometimes the extra 45kb is terrible but most of the time, and especially on personal project nobody should care. And if it is going to make your programming more efficient go with whatever works best for you.