如何解决RxJS 6.0.0中无法解析'rxjs/Rx'的编译错误?
Alright, let's break down this issue and get your code compiling again!
What's Causing This?
RxJS 6 made a deliberate change by removing the rxjs/Rx barrel import that was widely used in older versions. In RxJS 5.x and earlier, you could use import 'rxjs/Rx' to pull in every operator and core class in one go—but that's no longer supported in 6+. When your code tries to reference this path, the compiler can't locate it, hence the error you're seeing.
Solution 1: Update Your Imports (Recommended)
This is the official, long-term fix that also helps reduce your bundle size by only importing what you actually need:
- For core RxJS classes like
ObservableorSubject, import directly fromrxjs:import { Observable, Subject } from 'rxjs'; - For operators (like
map,filter,switchMap), import them fromrxjs/operatorsand use thepipe()method to chain them (this is RxJS 6's new standard syntax):import { map, filter } from 'rxjs/operators'; // Example usage this.http.get('/api/data').pipe( map(res => res.payload), filter(data => data.isActive) ).subscribe(result => { /* handle your result here */ }); - For static creation methods that used to be attached to
Observable(likeObservable.of()), import the standalone function fromrxjs:import { of } from 'rxjs'; // Replace Observable.of('test') with this of('test').subscribe(val => console.log(val));
Solution 2: Use rxjs-compat for Temporary Compatibility
If you've got a ton of legacy RxJS code and don't want to rewrite everything at once, you can install the compatibility package to keep the old import syntax working:
- Open your terminal, navigate to your project root, and run:
Or if you use Yarn:npm install rxjs-compat --saveyarn add rxjs-compat - Once installed, the compiler will recognize
rxjs/Rxagain, and your old code will run without changes. Just keep in mind this adds extra weight to your bundle, so plan to migrate to the new import style over time.
Quick Note
Double-check that your Angular version is compatible with RxJS 6—RxJS 6 pairs with Angular 6 and above. If you're on an older Angular version, you might need to either upgrade Angular or adjust your RxJS version, but based on your error message, the import mismatch is the most likely culprit.
内容的提问来源于stack exchange,提问作者sudhaparayil

