关于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方式查找,问题解决。
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值