關於cannot find module 'xxxx’的一個可能解決方法。


關於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":

  1. /root/src/folder/moduleB.ts
  2. /root/src/folder/moduleB.d.ts
  3. /root/src/moduleB.ts
  4. /root/src/moduleB.d.ts
  5. /root/moduleB.ts
  6. /root/moduleB.d.ts
  7. /moduleB.ts
  8. /moduleB.d.ts
找的可以看出其並不會找到nodejs的node_modules中,node的方式則會找到nodejs中,類似上面的方式,如果我也是import{b} from "moduleB", 逐級向上查找,代碼如下所示:
 
  1. /root/src/node_modules/moduleB.js
  2. /root/src/node_modules/moduleB/package.json (if it specifies a "main" property)
  3. /root/src/node_modules/moduleB/index.js 

  4. /root/node_modules/moduleB.js
  5. /root/node_modules/moduleB/package.json (if it specifies a "main" property)
  6. /root/node_modules/moduleB/index.js 

  7. /node_modules/moduleB.js
  8. /node_modules/moduleB/package.json (if it specifies a "main" property)
  9. /node_modules/moduleB/index.js
所以在項目tsconfig.json中添加一句話
"moduleResolution": "node",
覆蓋掉默認配置classic,將能按node方式查找,問題解決。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM