Avoid usage of JS Map with Immutable Map

Viewed 463

How can I avoid the confusion of native Map with Immutable.Map?

I use immutable.js in a react project (ES6 or later, transpiled with babel). So a lot of files start with an import like:

import { Map } from 'immutable';

Everything is fine until somebody adds the above import to a file that uses native JS Map, so that new Map() becomes an Immutable.Map.

I could consequently import the whole immutable library (import Immutable from 'immutable';) and reference it using Immutable.Map. However, this has possibly impact on the size of the resulting code (the compiler is likely not able to figure out that not the whole imported lib is used) and probably does not look nice.

Are there better solutions? Can I somehow reference native JS Map specifically?

2 Answers

You have two options here. I like the first, but YMMV.

  1. Native JavaScript modules allow you to alias not just entire library imports, but individual named imports: import {Map as IMap} from 'immutable';. Now there's no conflict and your bundle size should be smaller. Added bonus: the intent of your code might become more clear to future maintainers who will now immediately know they're not dealing with normal native Maps.

  2. The actual constructor is a property of the global context: just reference window.Map which won't conflict with the one you imported into the module namespace.

I'd recommend either importing Map in your higher order component and passing it down to your component as prop or using an import alias (as proposed in @Jared Smiths answer)

HigherOrderComponent

import { Map } from 'immutable';


class HigherOrderComponent extends React.Component { 
    render() {
        return <myChildComponent map={Map} />;
    }
}

myChildComponent

class HigherOrderComponent extends React.Component { 
    componentDidMount () {
        this.myMap = new this.props.Map();
    }
    render() {
       // ...
    }
}
Related