Angular – .map is not a function

I’ve encountered really weird error. After I’ve removed clearly unused code, our Angular app stopped working. It did however pass lint tests and also the production build passed without problems. The error occurred only during runtime. The error said something like “map is not a function at blablabla” and on the first glance it was totally unrelated to the code where it occurred.

After long digging and googling I found the root cause. Somewhere in our app we used import ‘rxjs/RX’, which imported the whole RxJS library which is large. It has about 50+ operators. And because it was included in the bundle accidentally, the app magically worked. We never had to worry about manually importing the RxJs operators. That is until we fixed the unused and unrelated import, hehe.

Conclusion

So the conclusion is, never import rxjs/RX because it will increase your bundle code size. But include only the specific operators which you really use. You can do it in the main module (usually called the app.module.ts) or specifically in those files, where they are actually used.

 

totally unrelated image :)

My import statement in app.module.ts now looks like this

import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/bufferWhen';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/delay';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/publish';
import 'rxjs/add/operator/publishLast';
import 'rxjs/add/operator/take';
import 'rxjs/add/operator/takeWhile';
import 'rxjs/add/operator/timeout';
import 'rxjs/add/operator/withLatestFrom';

Which is much better than this

// never ever!
import 'rxjs/Rx';