Socket
Socket
Sign inDemoInstall

tsconfig-paths

Package Overview
Dependencies
4
Maintainers
2
Versions
50
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    tsconfig-paths

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


Version published
Maintainers
2
Install size
216 kB
Created

Package description

What is tsconfig-paths?

The tsconfig-paths npm package is used to map module paths based on the paths defined in the tsconfig.json file. This allows TypeScript developers to use custom path mappings to simplify imports in their projects. It is particularly useful for avoiding relative path hell and for making the codebase cleaner and more maintainable.

What are tsconfig-paths's main functionalities?

Custom Path Mapping

This feature allows you to map paths in your TypeScript project so that you can import modules using aliases instead of relative paths. The code sample demonstrates how to register custom path mappings using the tsconfig-paths package.

require('tsconfig-paths').register({ baseUrl: './', paths: { '@app/*': ['./src/app/*'] } });

Integration with Node.js

This feature enables you to integrate tsconfig-paths with Node.js so that when you run your TypeScript-compiled JavaScript files, the custom paths are resolved correctly. The code sample shows how to run a Node.js application with tsconfig-paths support using the -r (require) flag.

node -r tsconfig-paths/register src/server.ts

Command Line Interface

tsconfig-paths provides a CLI tool called tsconfig-paths-bootstrap that can be used to bootstrap the path mappings before running your application. This is useful when you want to ensure that the path mappings are applied before any module resolution takes place.

tsconfig-paths-bootstrap

Other packages similar to tsconfig-paths

Changelog

Source

[3.3.2] - 2018-05-07

Fixed

  • Adding json file extension to extends property, #40. Thanks to @cwhite-connectfirst for this fixing this!

Readme

Source

tsconfig-paths

npm version travis build coveralls coverage 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 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 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 physcial 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

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"

Bootstrap tsconfig-paths 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.

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.
tsConfigPaths.register({
    baseUrl,
    paths: tsConfig.compilerOptions.paths
});

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:

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.

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 tsConfigPath The paths where tsconfig.json is located.
 * @param baseUrl The baseUrl specified in tsconfig.
 * @param paths The paths specified in tsconfig.
 */
export function createMatchPath(
  absoluteBaseUrl: string,
  paths: { [key: string]: Array<string> }
): 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 signare 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 existance of a file at a path (useful for testing).
 * @param extensions File extensions to probe for (useful for testing).
 * @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)
): string | undefined

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.

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.

FAQs

Last updated on 07 May 2018

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc