# 模块 (Modules)

# 模块配置

# paths 和baseUrl


import * as $ from 'jquery'

1
2
3

当有paths参数时,baseUrl是必须的

{
  "compilerOptions": {
    "baseUrl": ".", // This must be specified if "paths" is.
    "paths": {
      "jquery": ["node_modules/jquery/dist/jquery"] // This mapping is relative to "baseUrl"
    }
  }
}

1
2
3
4
5
6
7
8
9

paths是相对于baseUrl


{
  "compilerOptions": {
    "baseUrl": "./src", // This must be specified if "paths" is.
    "paths": {
      "jquery": ["../node_modules/jquery/dist/jquery"] // This mapping is relative to "baseUrl"
    }
  }
}
1
2
3
4
5
6
7
8
9

复杂的配置用法

目录如下


projectRoot
├── folder1
│   ├── file1.ts (imports 'folder1/file2' and 'folder2/file3')
│   └── file2.ts
├── generated
│   ├── folder1
│   └── folder2
│       └── file3.ts
└── tsconfig.json



1
2
3
4
5
6
7
8
9
10
11
12
13

file1.ts 内容如下

imports 'folder1/file2' and 'folder2/file3'

1
2

tsconfig.json 配置如下

imports 'folder1/file2'寻找模块

  • "*": 意味着 <moduleName> => <baseUrl>/<moduleName>,所以 寻找 projectRoot/folder1/file2
  • "generated/*" :意味着模块名前面用generated填充, <moduleName> => <baseUrl>/generated/<moduleName>,也就是projectRoot/generated/folder1/file2
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "*": ["*", "generated/*"]
    }
  }
}

1
2
3
4
5
6
7
8
9

file1.ts寻找folder1/file2模块的过程如下

  1. *已匹配,并且通配符捕获了整个模块名称
  2. 尝试使用<baseUrl>/folder1/file2也就是projectRoot/folder1/file2
  3. 找到了
  4. 退出

file1.ts寻找folder2/file3模块的过程如下

  1. *已匹配,并且通配符捕获了整个模块名称
  2. 尝试使用<baseUrl>/folder2/file3也就是projectRoot/folder2/file3
  3. 没有找到
  4. 匹配第二个path
  5. 也就是 generated/folder2/file3
  6. projectRoot/generated/folder2/file3.ts
  7. 找到退出

# 虚拟目录 rootDirs (opens new window)