How to use rxjs operators inside a TypeScript app

2019-09-05 13:21发布

I have a very Typescript app and I want to use rxjs.

I did:

npm install --save-dev rxjs

then in the file main.ts:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/from';
import 'rxjs/add/operator/filter';

function test() {
    Observable.from([0,1,2,3,4])
    .filter((x) => x >= 2)
    .subscribe((x) => console.log(x));
}

I get a compilation error:

Module not found: Error: Cannot resolve module 'rxjs/add/observable/from'

In case you need: here is my gulpfile, using Webpack

Do you know what I'm missing ? Thank you guys

1条回答
smile是对你的礼貌
2楼-- · 2019-09-05 13:34

I was checking your webpack.config.js, where you missed to add the resolvable extensions.

The webpack says,

An array of extensions that should be used to resolve modules. For example, in order to discover CoffeeScript files, your array should contain the string ".coffee".

Default: [".webpack.js", ".web.js", ".js"]

IMPORTANT: Setting this option will override the default, meaning that webpack will no longer try to resolve modules using the default extensions. If you want modules that were required with their extension (e.g. require('./somefile.ext')) to be properly resolved, you must include an empty string in your array. Similarly, if you want modules that were required without extensions (e.g. require('underscore')) to be resolved to files with “.js” extensions, you must include ".js" in your array.

Since you are overriding the webpack's default resolve extension options, you have to tell the webpack that, please resolve the modules which has ['.js', '.ts', ''] extensions.

查看更多
登录 后发表回答