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.
Typescript by default mimics the Node.js runtime resolution strategy of modules. But it also allows the use of path mapping 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 exeute 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
If you require this package's
tsconfig-paths/register module it will read the
tsconfig.json and convert node's module loading calls into to physcial file paths that node can load.
yarn add --dev tsconfig-paths
npm install --save-dev tsconfig-paths
node -r tsconfig-paths/register main.js
ts-node -r tsconfig-paths/register main.ts
process.env.TS_NODE_PROJECT is set it will be used to resolved tsconfig.json
mocha --compilers ts:ts-node/register -r tsconfig-paths/register
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.
const tsConfig = ;const tsConfigPaths = ;const baseUrl = "./"; // Either absolute or relative path. If relative it's resolved to current working directory.tsConfigPaths;
Then run with:
node -r ./tsconfig-paths-bootstrap.js main.js
process.env.TS_NODE_PROJECTto resolve tsConfig.json and the specified baseUrl and paths.
The API consists of these functions:
This function will create a function that can match paths. It accepts
paths directly as they are specified in tsconfig and will handle resolving paths to absolute form. The created function has this signature:
(sourceFileName: string, requestedModule: string, readPackageJson: (packageJsonPath: string) => any, fileExists: any, extensions?: Array<string>)
Same structure as paths in tsconfig but all paths needs to be resolved to absolute paths. This function is lower level and requries that the paths as already been resolved to absolute form.