Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

tsconfig-paths

dividab159.5mMIT4.2.0TypeScript support: included

Load node modules according to tsconfig paths, in run-time or via API.

readme

tsconfig-paths

npm version build Coverage Status MIT license code style: prettier

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 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.

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 physical file paths that node can load.

How to install

yarn add --dev tsconfig-paths

or

npm install --save-dev tsconfig-paths

How to use

With node

node -r tsconfig-paths/register main.js

If process.env.TS_NODE_BASEURL is set it will override the value of baseUrl in tsconfig.json:

TS_NODE_BASEURL=./dist node -r tsconfig-paths/register main.js

With ts-node

ts-node -r tsconfig-paths/register main.ts

If process.env.TS_NODE_PROJECT is set it will be used to resolved tsconfig.json

With webpack

For webpack please use the tsconfig-paths-webpack-plugin.

With mocha and ts-node

As of Mocha >= 4.0.0 the --compiler was deprecated. 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.

mocha -r ts-node/register -r tsconfig-paths/register "test/**/*.ts"

With other commands

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.

With ts-node and VSCode

The following is an example configuration for the .vscode/launch.json.

{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug Functions",
      "request": "launch",
      "type": "node",
      "runtimeArgs": [
        "-r",
        "${workspaceFolder}/functions/node_modules/ts-node/register",
        "-r",
        "${workspaceFolder}/functions/node_modules/tsconfig-paths/register"
      ],
      "args": ["${workspaceFolder}/functions/src/index.ts"],
      "cwd": "${workspaceFolder}",
      "protocol": "inspector",
      "env": {
        "NODE_ENV": "development",
        "TS_NODE_PROJECT": "${workspaceFolder}/functions/tsconfig.json"
      },
      "outFiles": ["${workspaceFolder}/functions/lib/**/*.js"]
    }
  ]
}

Bootstrapping with explicit params

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.

For example, create a wrapper script called tsconfig-paths-bootstrap.js with the contents below:

const tsConfig = require("./tsconfig.json");
const tsConfigPaths = require("tsconfig-paths");

const baseUrl = "./"; // Either absolute or relative path. If relative it's resolved to current working directory.
const cleanup = tsConfigPaths.register({
  baseUrl,
  paths: tsConfig.compilerOptions.paths,
});

// When path registration is no longer needed
cleanup();

Then run with:

node -r ./tsconfig-paths-bootstrap.js main.js

Configuration Options

You can set options by passing them before the script path, via programmatic usage or via environment variables.

ts-node --project customLocation/tsconfig.json -r tsconfig-paths/register "test/**/*.ts"

CLI and Programmatic Options

Environment variable denoted in parentheses.

  • -P, --project [path] Path to TypeScript JSON project file (TS_NODE_PROJECT)

Config loading process

  1. Use explicit params passed to register
  2. Use process.env.TS_NODE_PROJECT to resolve tsConfig.json and the specified baseUrl and paths.
  3. Resolves tsconfig.json from current working directory and the specified baseUrl and paths.

Programmatic use

The public API consists of these functions:

register

export interface ExplicitParams {
  baseUrl: string;
  paths: { [key: string]: Array<string> };
  mainFields?: Array<string>;
  addMatchAll?: boolean;
}

/**
 * Installs a custom module load function that can adhere to paths in tsconfig.
 */
export function register(explicitParams: ExplicitParams): () => void;

This function will patch the node's module loading so it will look for modules in paths specified by tsconfig.json. A function is returned for you to reinstate Node's original module loading.

loadConfig

export function loadConfig(cwd: string = process.cwd()): ConfigLoaderResult;

export type ConfigLoaderResult =
  | ConfigLoaderSuccessResult
  | ConfigLoaderFailResult;

export interface ConfigLoaderSuccessResult {
  resultType: "success";
  absoluteBaseUrl: string;
  paths: { [key: string]: Array<string> };
}

export interface ConfigLoaderFailResult {
  resultType: "failed";
  message: string;
}

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.

createMatchPath

/**
 * Function that can match a path
 */
export interface MatchPath {
  (
    requestedModule: string,
    readJson?: Filesystem.ReadJsonSync,
    fileExists?: (name: string) => boolean,
    extensions?: ReadonlyArray<string>
  ): string | undefined;
}

/**
 * Creates a function that can resolve paths according to tsconfig paths property.
 * @param absoluteBaseUrl Absolute version of baseUrl as specified in tsconfig.
 * @param paths The paths as specified in tsconfig.
 * @param mainFields A list of package.json field names to try when resolving module files.
 * @param addMatchAll Add a match-all "*" rule if none is present
 * @returns a function that can resolve paths.
 */
export function createMatchPath(
  absoluteBaseUrl: string,
  paths: { [key: string]: Array<string> },
  mainFields: string[] = ["main"],
  addMatchAll: boolean = true
): MatchPath {

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 signature specified by the type MatchPath above.

matchFromAbsolutePaths

/**
 * Finds a path from tsconfig that matches a module load request.
 * @param absolutePathMappings The paths to try as specified in tsconfig but resolved to absolute form.
 * @param requestedModule The required module name.
 * @param readJson Function that can read json from a path (useful for testing).
 * @param fileExists Function that checks for existence of a file at a path (useful for testing).
 * @param extensions File extensions to probe for (useful for testing).
 * @param mainFields A list of package.json field names to try when resolving module files.
 * @returns the found path, or undefined if no path was found.
 */
export function matchFromAbsolutePaths(
  absolutePathMappings: ReadonlyArray<MappingEntry.MappingEntry>,
  requestedModule: string,
  readJson: Filesystem.ReadJsonSync = Filesystem.readJsonFromDiskSync,
  fileExists: Filesystem.FileExistsSync = Filesystem.fileExistsSync,
  extensions: Array<string> = Object.keys(require.extensions),
  mainFields: string[] = ["main"]
): string | undefined {

This function is lower level and requires that the paths as already been resolved to absolute form and sorted in correct order into an array.

createMatchPathAsync

This is the async version of createMatchPath. It has the same signature but with a callback parameter for the result.

matchFromAbsolutePathsAsync

This is the async version of matchFromAbsolutePaths. It has the same signature but with a callback parameter for the result.

How to publish

yarn version --patch
yarn version --minor
yarn version --major

changelog

Change Log

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog and this project adheres to Semantic Versioning.

Unreleased

[4.2.0] - 2023-03-29

Added

  • Add support for tsconfig extends as array of strings. #. See PR #245. Thanks to @DanielSidhion for this PR!

[3.14.2] - 2023-02-25

Fixed

  • bump JSON5 from v1.0.1 to v1.0.2 in tsconfig-paths v3.14.1 to fix CVE-2022-46175 #234. See PR #234. Thanks to @mihaiplesa for this PR!

[4.1.2] - 2023-01-02

Fixed

  • Bump JSON5 dependency to 2.2.2 to fix CVE-2022-46175. See PR #232. Thanks to @oparisblue for this PR!

[4.1.1] - 2022-11-30

Fixed

  • Skip stat call / throwing an exception when source files don't exist. See PR #225. Thanks to @robstolarz for this PR!

[4.1.0] - 2022-08-06

  • Add support for nested main field selectors #. See PR #218. Thanks to @aaronadamsCA for this PR!

[4.0.0] - 2022-05-02

Changed

  • Ignore --project/-P CLI flag when explicit options are passed to register. See PR #206.
  • Tolerate an undefined baseUrl compiler option. See PR #208.

Added

  • Add cwd option to register function that overrides where the tsconfig.json search begins. See PR #205.
  • Add support for jsconfig.json. See PR #199. Thanks to @F3n67u for this PR!
  • Let paths mappings be absolute paths. See PR #184.
  • Allow baseUrl in tsconfig.json to be an absolute path. See PR #174. Thanks to @nwalters512 for this PR!

[3.14.1] - 2022-03-22

Fixed

  • Use minimist 1.2.6 for all depencencies becuase of pollution vulnerability. See PR #197. Thanks to @gopijaganthan for this fix!

[3.14.0] - 2022-03-13

Added

  • Support for path mapping starting with /. See PR #180, issue #113, and issue #128. Thanks to @benevbright for this fix!

[3.13.0] - 2022-03-03

Added

  • Include file extension in paths resolved from package.json "main" field. See PR #135 and issue #133. Thanks to @katywings for this fix!

[3.12.0] - 2021-08-24

  • Add support for baseUrl override using TS_NODE_BASEURL env var #185 and #114. Thanks to @ejhayes and @information-security for these PRs!

[3.11.0] - 2021-08-24

  • Reverted upgrade of json5 due to being a breaking change. See PR #173.

[3.10.1] - 2021-07-06

Fixed

  • Add register.js to published files

[3.10.0] - 2021-07-06

Added

  • feat(tsconfig-loader): extends config from node_modules (#106). Thanks to @zorji for this PR!

Fixed

  • Update CHANGELOG.md (#96). Thanks to @OliverJAsh for this PR!
  • Fix "bootstraping" typo (#111). Thanks to @KRMisha for this PR!
  • Update Readme fixes #116 (#123). Thanks to @benwinding for this PR!
  • Fixed typo (#144). Thanks to @mprinc for this PR!
  • [TYPO] src/mapping-entry.ts (#145). Thanks to @mprinc for this PR!
  • docs(README): fix typos (#156). Thanks to @PiDelport for this PR!
  • deps: bump json5 to use type definition provided officially (#158). Thanks to @koba04 for this PR!
  • Update tsconfig-loader.ts (#161). Thanks to @fecqs for this PR!
  • fix typo (#165). Thanks to @wonda-tea-coffee for this PR!
  • Add file extenstion to typings property value (#151). Thanks to @dangrussell for this PR!

3.9.0 - 2019-09-12

Added

  • Make extension config override instead of deep merge. See PR #95 and issue #94. Thanks to @OliverJAsh for this addition!

3.8.0 - 2019-02-05

Added

  • Add option to avoid adding a match-all rule. See PR #73 and issue 72. Thanks to @Swatinem for this addition!

3.7.0 - 2018-11-11

Added

  • Allow cleanup of register(). See PR #64 and issue 63. Thanks to @TylorS for this addition!

3.6.0 - 2018-09-10

Added

  • Prefer Node's core modules over file modules. See PR #60 and issue 56. Thanks to @ljani for this addition!

3.5.0 - 2018-07-28

Added

  • Add support for trailing commas in tsconfig.json (use JSON5 to parse). See issue #48, and PR #58. Thanks to @jshado1 for this addition!

3.4.2 - 2018-06-30

Fixed

  • Do not resolve directories, only files, sse issue #51.

3.4.1 - 2018-06-24

Fixed

  • Ignore field name mappings in package.json files that are not paths of existing files #46. Thanks to @christoffer for this fix!

3.4.0 - 2018-06-12

Added

  • Add support for providing a list of field names to try instead of just using "main", #45. Thanks to @christoffer-dropbox for this addition!

3.3.2 - 2018-05-07

Fixed

3.3.1 - 2018-04-17

Fixed

  • Fix project undefined error when calling register, #37. Thanks to @natedanner for this fixing this!

3.3.0 - 2018-04-14

Added

  • Add possibility to indicate explicitly tsconfig location, #35. Thanks to @procopenco for this adding this!

3.2.0 - 2018-03-31

Added

  • Added support for passing a filename as cwd, see issue #31 and PR #32. Thanks to @amodm for this adding this!

3.1.3 - 2018-03-14

Fixed

  • Fix async recursion, see #30. Thanks to @Nayni for this fix!

3.1.2 - 2018-03-13

Fixed

  • Fix a forgotten return when doneCallback is invoked, see #29. Thanks to @Nayni for this fix!

3.1.1 - 2018-01-13

Fixed

  • Fix read json async when it does not exist

3.1.0 - 2018-01-13

Added

  • Implement default async json reader function.

3.0.0 - 2018-01-13

Changed

  • Remove parameter absoluteSourceFileName from the MatchPath and matchFromAbsolutePaths functions. It was not used internally.
  • matchFromAbsolutePaths now accepts a pre-sorted array of MappingEntrys instead of a dictionary. This was done so the sorting could be done once which should give better performance.

Added

  • createMatchPathAsync, creates an async version of the MatchPath function. Can be used for example by webpack plugins.
  • matchFromAbsolutePathsAsync, async version of matchFromAbsolutePaths.

2.7.3

Fixed

  • Only resolve path if tsconfig present #25. Thanks to @nicoschoenmaker for the PR.

2.7.2

Fixed

  • Return absolute path to tsconfig.json.

2.7.1

Fixed

  • Remove left over console.log.

2.7.0

Added

  • Support baseUrl to exist in base tsconfig.json when using extends, see #23.

2.6.0

Added

  • Add baseUrl and configFileAbsolutePath to the result of loadConfig.

2.5.0

Added

  • New function in Programmatic API loadConfig.

2.4.3

Fixed

  • Export MatchPth typing.

2.4.2

Fixed

  • Add missing types field in package.json.

2.4.1

Fixed

  • Include declaration files. Fixes #22.

2.4.0

Changed

  • Removed dependency for package tsconfig.

Fixed

  • Support for config inheritance with extends. Fixes #17.

2.2.0

Fixed

  • Fixed issue #7.

2.1.2

Fixed

  • Fixed issue #6.

2.1.1

Fixed

  • Fixed issue #4

[2.1.0]

Fixed

  • Fixed issue #3

[2.0.0]

Added

  • We now look at process.env.TS_NODE_PROJECT
  • Functionality to bootstrap tsconfig-paths. Documentation in README

Changed

  • Changed signature for createMatchPath. Now only takes absoluteUrl and paths.

[1.1.0]

Added

  • More explanation to readme.
  • Match all extensions in require.extensions.
  • Match longest pattern prefix first as typesript does.
  • Match file in main field of package.json.
  • Check for index files explicitly.

[1.0.0] - 2016-12-30

  • First stable release.

[0.4.0] - 2016-12-30

Changed

  • Renamed project to tsocnfig-paths.

[0.3.0] - 2016-12-30

Added

  • API documentation.
  • createMatchPath function.
  • matchFromAbsolutePaths function.

Removed

  • findPath function.

[0.2.1] - 2016-12-29

Fixed

  • tsconfig-paths/register was not available.

[0.2.0] - 2016-12-29

Fixed

  • Paths for files in sub-dirs.

Added

  • Programmatic use.

[0.1.2] - 2016-12-28

Fixed

  • Fixed wrong name of the package in README.
  • Add missing files on publish.

[0.1.1] - 2016-12-28

Added

  • Loading of tsconfig.
  • Example.
  • Publish scripts.

[0.1.0] - 2016-12-28

  • Initial version.