關於cannot find module 'xxxx’的一個可能解決方法。
由於學習angular2,想單獨學習一下typescript下angular2使用的‘rxjs’是怎么使用的,我用npm自己安裝了rxjs,並使用了如下語句
import { Observable } from 'rxjs';
報錯如下:
cannot find module 'rxjs',
但是同樣的語句在angular/cli生成的angular項目下是不報錯的,我找了半天,各種解決方法都不適用於我遇到的情況。由於這個是typescript import時報的錯誤,我查看了typescript module對應的講解:
Module Resolution Strategies
There are two possible module resolution strategies:
Node and
Classic. You can use the
--moduleResolution flag to specify the module resolution strategy. If not specified, the default is
Classic for
--module AMD | System | ES2015or
Node otherwise.
也就是說typescript是有兩種module管理的方式的,默認的不是node,是classic,我們看看node和classic分別是怎么進行import時的module查找的,我只說non-relative的情況,因為我這里要找node_modules下的第三方包,屬於nonrelative:
先說classic:
Classic
This used to be TypeScript’s default resolution strategy. Nowadays, this strategy is mainly present for backward compatibility.
For non-relative module imports, however, the compiler walks up the directory tree starting with the directory containing the importing file, trying to locate a matching definition file.
For example:
A non-relative import to moduleB such as import { b } from "moduleB", in a source file /root/src/folder/A.ts, would result in attempting the following locations for locating "moduleB":
/root/src/folder/moduleB.ts/root/src/folder/moduleB.d.ts/root/src/moduleB.ts/root/src/moduleB.d.ts/root/moduleB.ts/root/moduleB.d.ts/moduleB.ts/moduleB.d.ts
找的可以看出其並不會找到nodejs的node_modules中,node的方式則會找到nodejs中,類似上面的方式,如果我也是import{b} from "moduleB", 逐級向上查找,代碼如下所示:
/root/src/node_modules/moduleB.js/root/src/node_modules/moduleB/package.json(if it specifies a"main"property)/root/src/node_modules/moduleB/index.js/root/node_modules/moduleB.js/root/node_modules/moduleB/package.json(if it specifies a"main"property)/root/node_modules/moduleB/index.js/node_modules/moduleB.js/node_modules/moduleB/package.json(if it specifies a"main"property)/node_modules/moduleB/index.js
所以在項目tsconfig.json中添加一句話
"moduleResolution": "node",
覆蓋掉默認配置classic,將能按node方式查找,問題解決。
