0

There's something I'm not sure to understand with ES6 modules, especially when it comes to import with side effects.

For example, in an Angular project, I'm using Rxjs library to use observables. I need to import functions and objects from this library with ES6 import.

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/of';

//later in the code I'm using these imports like this in a method
return Obserable.of(....);

My problem is with imports : import { Observable } from 'rxjs/Observable'; seems understandable: I'm importing Observable object from 'rxjs/Obserable' located in node_modules.

My problem is with import 'rxjs/add/observable/of'; Why not something like import { of } from 'rxjs/....';

I've read import '...' doesn't export any object or function. What does it do exactly ? If you are not exporting 'of' operator, how can you use it ? When to use import */import {} from or directly import '...';

Thanks

1 Answer 1

1

That's actually old way to import operators.

import 'rxjs/add/observable/of'; is actually prototyping method of to Observable. When you import that, every Observable object has of method available. That's why you should put those import lines in a root file like app.module. However, as I told you at the beginning, it is the old way.

With RxJs 5.5, pipeable operators came into play. You can and should import operators/observables as follows

import { of } from 'rxjs/observable/of';

const myObs = of('some value');

With this way, operators and observables became tree-shakable. Webpack will not put unused operators into your output bundle.

Update

Let's say you are using bunch of operators and you added static imports in a global file. After a while, you refactored your code and you are no longer using Observable.of. But let's say you forgot you already imported that in a global file. Even though you are not using of anymore, you are still going to get the code of of observable in your output bundle. Prototyping makes it impossible to tree shake your code. I suggest you watch this. Ben Lesh explains pipeable operators and RxJs6.

Sign up to request clarification or add additional context in comments.

1 Comment

Ok thanks. So using the syntax " import '...' " is used to add prototypes properties or modifying global scope with polyfills, stuff like that contrary to "import {...} from...", is that correct ? Also I don't understand your last part about Webpack and unused operators. When using the old syntax import 'rxjs/add/observable/of'; you are just using the 'of' operator. I don't see any unused operators, I'm just importing what I need

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.