web 3d图形渲染器
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

231 lines
8.4 KiB

  1. # tsconfig-paths
  2. [![npm version][version-image]][version-url]
  3. [![travis build][travis-image]][travis-url]
  4. [![Coverage Status][codecov-image]][codecov-url]
  5. [![MIT license][license-image]][license-url]
  6. [![code style: prettier][prettier-image]][prettier-url]
  7. Use this to load modules whose location is specified in the `paths` section of `tsconfig.json`. Both loading at run-time and via API are supported.
  8. Typescript by default mimics the Node.js runtime resolution strategy of modules. But it also allows the use of [path mapping](https://www.typescriptlang.org/docs/handbook/module-resolution.html) which allows arbitrary module paths (that doesn't start with "/" or ".") to be specified and mapped to physical paths in the filesystem. The typescript compiler can resolve these paths from `tsconfig` so it will compile OK. But if you then try to execute the compiled files with node (or ts-node), it will only look in the `node_modules` folders all the way up to the root of the filesystem and thus will not find the modules specified by `paths` in `tsconfig`.
  9. If you require this package's `tsconfig-paths/register` module it will read the `paths` from `tsconfig.json` and convert node's module loading calls into to physcial file paths that node can load.
  10. ## How to install
  11. ```
  12. yarn add --dev tsconfig-paths
  13. ```
  14. or
  15. ```
  16. npm install --save-dev tsconfig-paths
  17. ```
  18. ## How to use
  19. ### With node
  20. `node -r tsconfig-paths/register main.js`
  21. ### With ts-node
  22. `ts-node -r tsconfig-paths/register main.ts`
  23. If `process.env.TS_NODE_PROJECT` is set it will be used to resolved tsconfig.json
  24. ### With webpack
  25. For webpack please use the [tsconfig-paths-webpack-plugin](https://github.com/dividab/tsconfig-paths-webpack-plugin).
  26. ### With mocha and ts-node
  27. As of Mocha >= 4.0.0 the `--compiler` was [deprecated](https://github.com/mochajs/mocha/wiki/compilers-deprecation). Instead `--require` should be used. You also have to specify a glob that includes `.ts` files because mocha looks after files with `.js` extension by default.
  28. ```bash
  29. mocha -r ts-node/register -r tsconfig-paths/register "test/**/*.ts"
  30. ```
  31. ### With other commands
  32. As long as the command has something similar to a `--require` option that can load a module before it starts, tsconfig-paths should be able to work with it.
  33. ## Bootstraping with explicit params
  34. If you want more granular control over tsconfig-paths you can bootstrap it. This can be useful if you for instance have compiled with `tsc` to another directory where `tsconfig.json` doesn't exists.
  35. ```javascript
  36. const tsConfig = require("./tsconfig.json");
  37. const tsConfigPaths = require("tsconfig-paths");
  38. const baseUrl = "./"; // Either absolute or relative path. If relative it's resolved to current working directory.
  39. const cleanup = tsConfigPaths.register({
  40. baseUrl,
  41. paths: tsConfig.compilerOptions.paths
  42. });
  43. // When path registration is no longer needed
  44. cleanup();
  45. ```
  46. Then run with:
  47. `node -r ./tsconfig-paths-bootstrap.js main.js`
  48. ## Configuration Options
  49. You can set options by passing them before the script path, via programmatic usage or via environment variables.
  50. ```bash
  51. ts-node --project customLocation/tsconfig.json -r tsconfig-paths/register "test/**/*.ts"
  52. ```
  53. ### CLI and Programmatic Options
  54. _Environment variable denoted in parentheses._
  55. - `-P, --project [path]` Path to TypeScript JSON project file (`TS_NODE_PROJECT`)
  56. ## Config loading process
  57. 1. Use explicit params passed to register
  58. 2. Use `process.env.TS_NODE_PROJECT` to resolve tsConfig.json and the specified baseUrl and paths.
  59. 3. Resolves tsconfig.json from current working directory and the specified baseUrl and paths.
  60. ## Programmatic use
  61. The public API consists of these functions:
  62. - [register](#register)
  63. - [loadConfig](#loadConfig)
  64. - [createMatchPath](#createMatchPath) / [createMatchPathAsync](#createMatchPathAsync)
  65. - [matchFromAbsolutePaths](#matchFromAbsolutePaths) / [matchFromAbsolutePathsAsync](#matchFromAbsolutePathsAsync)
  66. ### register
  67. ```typescript
  68. export interface ExplicitParams {
  69. baseUrl: string;
  70. paths: { [key: string]: Array<string> };
  71. mainFields?: Array<string>;
  72. addMatchAll?: boolean;
  73. }
  74. /**
  75. * Installs a custom module load function that can adhere to paths in tsconfig.
  76. */
  77. export function register(explicitParams: ExplicitParams): () => void;
  78. ```
  79. This function will patch the node's module loading so it will look for modules in paths specified by tsconfig.json.
  80. A function is returned for you to reinstate Node's original module loading.
  81. ### loadConfig
  82. ```typescript
  83. export function loadConfig(cwd: string = process.cwd()): ConfigLoaderResult;
  84. export type ConfigLoaderResult =
  85. | ConfigLoaderSuccessResult
  86. | ConfigLoaderFailResult;
  87. export interface ConfigLoaderSuccessResult {
  88. resultType: "success";
  89. absoluteBaseUrl: string;
  90. paths: { [key: string]: Array<string> };
  91. }
  92. export interface ConfigLoaderFailResult {
  93. resultType: "failed";
  94. message: string;
  95. }
  96. ```
  97. This function loads the tsconfig.json. It will start searching from the specified `cwd` directory. Passing the tsconfig.json file directly instead of a directory also works.
  98. ### createMatchPath
  99. ```typescript
  100. /**
  101. * Function that can match a path
  102. */
  103. export interface MatchPath {
  104. (
  105. requestedModule: string,
  106. readJson?: Filesystem.ReadJsonSync,
  107. fileExists?: (name: string) => boolean,
  108. extensions?: ReadonlyArray<string>
  109. ): string | undefined;
  110. }
  111. /**
  112. * Creates a function that can resolve paths according to tsconfig paths property.
  113. * @param absoluteBaseUrl Absolute version of baseUrl as specified in tsconfig.
  114. * @param paths The paths as specified in tsconfig.
  115. * @param mainFields A list of package.json field names to try when resolving module files.
  116. * @param addMatchAll Add a match-all "*" rule if none is present
  117. * @returns a function that can resolve paths.
  118. */
  119. export function createMatchPath(
  120. absoluteBaseUrl: string,
  121. paths: { [key: string]: Array<string> },
  122. mainFields: string[] = ["main"],
  123. addMatchAll: boolean = true
  124. ): MatchPath {
  125. ```
  126. The `createMatchPath` function will create a function that can match paths. It accepts `baseUrl` and `paths` directly as they are specified in tsconfig and will handle resolving paths to absolute form. The created function has the signare specified by the type `MatchPath` above.
  127. ### matchFromAbsolutePaths
  128. ```typescript
  129. /**
  130. * Finds a path from tsconfig that matches a module load request.
  131. * @param absolutePathMappings The paths to try as specified in tsconfig but resolved to absolute form.
  132. * @param requestedModule The required module name.
  133. * @param readJson Function that can read json from a path (useful for testing).
  134. * @param fileExists Function that checks for existance of a file at a path (useful for testing).
  135. * @param extensions File extensions to probe for (useful for testing).
  136. * @param mainFields A list of package.json field names to try when resolving module files.
  137. * @returns the found path, or undefined if no path was found.
  138. */
  139. export function matchFromAbsolutePaths(
  140. absolutePathMappings: ReadonlyArray<MappingEntry.MappingEntry>,
  141. requestedModule: string,
  142. readJson: Filesystem.ReadJsonSync = Filesystem.readJsonFromDiskSync,
  143. fileExists: Filesystem.FileExistsSync = Filesystem.fileExistsSync,
  144. extensions: Array<string> = Object.keys(require.extensions),
  145. mainFields: string[] = ["main"]
  146. ): string | undefined {
  147. ```
  148. This function is lower level and requries that the paths as already been resolved to absolute form and sorted in correct order into an array.
  149. ### createMatchPathAsync
  150. This is the async version of `createMatchPath`. It has the same signature but with a callback parameter for the result.
  151. ### matchFromAbsolutePathsAsync
  152. This is the async version of `matchFromAbsolutePaths`. It has the same signature but with a callback parameter for the result.
  153. ## How to publish
  154. ```
  155. yarn version --patch
  156. yarn version --minor
  157. yarn version --major
  158. ```
  159. [version-image]: https://img.shields.io/npm/v/tsconfig-paths.svg?style=flat
  160. [version-url]: https://www.npmjs.com/package/tsconfig-paths
  161. [travis-image]: https://travis-ci.com/dividab/tsconfig-paths.svg?branch=master&style=flat
  162. [travis-url]: https://travis-ci.com/dividab/tsconfig-paths
  163. [codecov-image]: https://codecov.io/gh/dividab/tsconfig-paths/branch/master/graph/badge.svg
  164. [codecov-url]: https://codecov.io/gh/dividab/tsconfig-paths
  165. [license-image]: https://img.shields.io/github/license/dividab/tsconfig-paths.svg?style=flat
  166. [license-url]: https://opensource.org/licenses/MIT
  167. [prettier-image]: https://img.shields.io/badge/code_style-prettier-ff69b4.svg
  168. [prettier-url]: https://github.com/prettier/prettier