TypeScript和Node模块解析策略

一般我们在模块化编码时,总会导入其它模块,通常我们使用如下语法:

import { A } from './a'; // ES6语法
import { A } from 'a';
var A = require('./a'); // commonjs规范

不论使用哪种语法,导入的文件一般有两种:内部文件(自己开发的)和外部(node_modules)中两种,其中导入内部模块称之为相对导入,导入node_modules中,称之为非相对导入,它们在语法上的区别就是导入的路径是否是相对的

接下来我们看看typescript和node中它们是如何解析模块的

Typescript模块解析策略

相对导入

假如b.ts路径是:/root/src/b.ts

import { A } from './a';

typescript编译器在查找a模块时会依次按照如下顺序查找,如果仍然找不到则会模块找不到的错误。

/root/src/a.ts
/root/src/a.tsx
/root/src/a.d.ts
/root/src/a/package.json (如果指定了"types"属性,则使用types中)
/root/src/a/index.ts
/root/src/a/index.tsx
/root/src/a/index.d.ts

非相对导入

假如b.ts路径是:/root/src/b.ts

import { A } from 'a';

typescript编译器在查找a模块时会按照如下顺序查找:

/root/src/node_modules/a.ts
/root/src/node_modules/a.tsx
/root/src/node_modules/a.d.ts
/root/src/node_modules/a/package.json
/root/src/node_modules/a/index.ts
/root/src/node_modules/a/index.tsx
/root/src/node_modules/a/index.d.ts

/root/node_modules/a.ts
/root/node_modules/a.tsx
/root/node_modules/a.d.ts
/root/node_modules/a/package.json
/root/node_modules/a/index.ts
/root/node_modules/a/index.tsx
/root/node_modules/a/index.d.ts

/node_modules/a.ts
/node_modules/a.tsx
/node_modules/a.d.ts
/node_modules/a/package.json
/node_modules/a/index.ts
/node_modules/a/index.tsx
/node_modules/a/index.d.ts

其中在上面两处空白行处,编译器会跳到上一级目录查找,直到到工程根目录

注意:有时候我们在导入外部模块(没有ts文件,只有),编译器会报模块找不到,但是我们node_modules确实有,这种方式不是编译器bug而需要我们在配置文件tsconfig.json中修改模块解析策略:

 "moduleResolution": "node"

说到这里我们看看Nodejs时如何解析模块的,NodeJs使用了commonjs模块规范,typescript编译和其大同小异。

Nodejs相对导入

假如b.ts路径是:/root/src/b.js

var A = require('./a')

typescript编译器在查找a模块时会按照如下顺序查找:

/root/src/a
/root/src/a.js
/root/src/a.json
/root/src/a/package.json (如果指定了"main"属性,则使用main中的)
/root/src/a/index.js
/root/src/a/index.json

上述第二步中,假如main:"./core/main.js",则最终模块路径:

/root/src/a/core/main.js

Nodejs非相对导入

var A = require('a')

typescript编译器在查找a模块时会按照如下顺序查找:

/root/src/node_modules/a.js
/root/src/node_modules/a/package.json (如果指定了"main"属性,则使用main中的)
/root/src/node_modules/a/index.js

/root/node_modules/a.js
/root/node_modules/a/package.json (如果指定了"main"属性,则使用main中的)
/root/node_modules/a/index.js

/node_modules/a.js
/node_modules/a/package.json (如果指定了"main"属性,则使用main中的)
/node_modules/a/index.js

转载于:https://www.cnblogs.com/winfred/p/8179815.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值