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