### tsconfig.json with references Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/project-references.md Example root tsconfig.json showing the 'references' array with a path to './core'. Used to illustrate how 'followReferences' resolves project references. ```json // tsconfig.json (root) { "references": [{ "path": "./core" }] } ``` -------------------------------- ### tsconfig tsc-alias configuration example Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/configuration.md Example tsconfig.json showing the tsc-alias section with paths, verbose, resolveFullPaths, replacers, and fileExtensions. The replacers' file paths are joined onto the tsconfig directory. ```json { "compilerOptions": { "paths": { "@app/*": ["./src/*"] } }, "tsc-alias": { "verbose": false, "resolveFullPaths": true, "replacers": { "exampleReplacer": { "enabled": true, "file": "./exampleReplacer.js" }, "otherReplacer": { "enabled": true, "file": "./otherReplacer.js" } }, "fileExtensions": { "inputGlob": "{js,jsx,mjs}", "outputCheck": ["js", "json", "jsx", "mjs"] } } } ``` -------------------------------- ### Full-featured invocation with resolveFullPaths, followReferences, verbose Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/main.md Shows all main options: resolveFullPaths, resolveFullExtension, resolvePackageSubpaths, followReferences, fileExtensions, and verbose. Use when you need to resolve incomplete import paths, follow referenced projects, and get verbose output. ```TypeScript import { replaceTscAliasPaths } from 'tsc-alias'; await replaceTscAliasPaths({ configFile: 'tsconfig.json', resolveFullPaths: true, // resolve incomplete import paths (.js extension) resolveFullExtension: '.mjs', // extension used while resolving full paths resolvePackageSubpaths: true, // resolve bare-package subpath imports too followReferences: true, // also rewrite referenced projects fileExtensions: { inputGlob: '{js,jsx,mjs}', outputCheck: ['js', 'json', 'jsx', 'mjs'] }, verbose: true }); ``` -------------------------------- ### Handling the `---` sentinel Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/path-cache.md Imports PathCache from the internal module and creates a cache with watch=true, extensions ['js','json'], and a tsconfig path. Calls getAbsoluteAliasPath to resolve an alias; if the result starts with '---', it indicates no existing artifact, otherwise it logs the resolved path. ```ts import { PathCache } from 'tsc-alias/dist/utils/path-cache'; // internal module const cache = new PathCache(true, ['js', 'json'], '/project/tsconfig.json'); const resolved = cache.getAbsoluteAliasPath('/project/dist', 'utils/helper'); if (resolved.startsWith('---')) { console.log('no existing artifact for:', resolved.slice(3)); } else { console.log('resolved to', resolved); } ``` -------------------------------- ### replaceAlias round-trip with change detection Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/replace-alias.md Example from the 'replaceAlias round-trip with change detection' section. Uses prepareConfig with resolveFullPaths: true and replaceAlias; replaceAlias returns a boolean indicating whether the file was rewritten, and the example logs a message when changed. ```TypeScript import { prepareConfig } from 'tsc-alias/dist/helpers'; import { replaceAlias } from 'tsc-alias/dist/helpers/replace-alias'; const config = await prepareConfig({ configFile: 'tsconfig.json', resolveFullPaths: true }); const changed = await replaceAlias({ config, file: '/project/dist/index.js' }); if (changed) { console.log('/project/dist/index.js was rewritten'); } ``` -------------------------------- ### Install tsc-alias as devDependency with npm Source: https://github.com/justkey007/tsc-alias/blob/master/README.md Installs tsc-alias as a local devDependency using npm. ```sh npm install --save-dev tsc-alias ``` -------------------------------- ### Configure tsc-alias via tsconfig.json Source: https://github.com/justkey007/tsc-alias/blob/master/README.md Example tsconfig.json configuration with tsc-alias options including replacers and fileExtensions. ```json { "compilerOptions": { ... }, "tsc-alias": { "verbose": false, "resolveFullPaths": true, "replacers": { "exampleReplacer": { "enabled": true, "file": "./exampleReplacer.js" }, "otherReplacer": { "enabled": true, "file": "./otherReplacer.js" } }, "fileExtensions": { "inputGlob": "{js,jsx,mjs}", "outputCheck": ["js", "json", "jsx", "mjs"] } } } ``` -------------------------------- ### Install tsc-alias via npm Source: https://github.com/justkey007/tsc-alias/blob/master/README.md Install the tsc-alias package using npm. ```sh npm install tsc-alias ``` -------------------------------- ### Install tsc-alias globally with npm Source: https://github.com/justkey007/tsc-alias/blob/master/README.md Installs tsc-alias as a global devDependency using npm. ```sh npm install -g tsc-alias ``` -------------------------------- ### Using declarationDir for .d.ts files Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/single-file-replacer.md Configures the replacer with outDir, declarationDir, and resolveFullPaths so .d.ts files in the declaration output resolve aliases correctly. The example shows rewriting a .d.ts file's contents. ```ts import { prepareSingleFileReplaceTscAliasPaths } from 'tsc-alias'; const replacer = await prepareSingleFileReplaceTscAliasPaths({ configFile: 'tsconfig.json', outDir: 'dist', declarationDir: 'dist/types', resolveFullPaths: true }); // .d.ts files in dist/types automatically use the declaration config const rewrittenDts = replacer({ fileContents: `import { helper } from '@app/utils';`, filePath: '/project/dist/types/index.d.ts' }); ``` -------------------------------- ### replaceAliasString: ordering matters (replacers first, full-path resolution second) Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/replace-alias.md Example from the 'Ordering matters: replacers first, full-path resolution second' section. Shows that replaceAliasString first runs replacers (step 1) and then resolveFullPath (step 2). The comments illustrate the transformation: '@lib/b' aliased to a directory without an extension becomes './b' after the replacer and './b.js' after full-path resolution. ```TypeScript const out = replaceAliasString({ config, file: '/project/dist/a.js', code: `import { b } from '@lib/b';` // '@lib/b' is aliased to a directory without an extension // step 1 (replacer): → `import { b } from './b';` // step 2 (resolveFullPath): → `import { b } from './b.js';` }); ``` -------------------------------- ### replaceAliasString: transforming a string in memory Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/replace-alias.md Example from the 'Transforming a string in memory' section. Uses internal modules from tsc-alias/dist/helpers. prepareConfig reads tsconfig.json, then replaceAliasString rewrites the provided code string and returns the new content; with resolveFullPath: true and resolveFullExtension: '.js', the output is e.g. `import { foo } from './foo.js';`. ```TypeScript import { prepareConfig } from 'tsc-alias/dist/helpers'; // internal module import { replaceAliasString } from 'tsc-alias/dist/helpers/replace-alias'; // internal module const config = await prepareConfig({ configFile: 'tsconfig.json' }); const out = replaceAliasString({ config, file: '/project/dist/index.js', code: `import { foo } from '@app/foo';`, resolveFullPath: true, resolveFullExtension: '.js' }); console.log(out); // e.g. `import { foo } from './foo.js';` ``` -------------------------------- ### Custom Output Implementation with IOutput Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/output.md Shows how to implement the IOutput interface to customize or disable tsc-alias output. The example throws exceptions instead of calling process.exit and uses a custom assert that throws on failure. Pass the object to replaceTscAliasPaths via the output option. ```typescript import { Output } from 'tsc-alias/dist/utils/output'; // internal deep import (not public API) import { Output as MyOutput } from './my-output'; // Implementing IOutput yourself is the supported way to customize/disable output: const quietOutput: IOutput = { verbose: false, debug: () => {}, info: () => {}, clear: () => {}, error: (message, exitProcess = false) => { throw new Error(message); // exceptions instead of process.exit }, assert: (claim, message) => { if (!claim) throw new Error(message); } }; await replaceTscAliasPaths({ output: quietOutput }); ``` -------------------------------- ### Advanced usage with custom IOutput to intercept errors Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/main.md Provides a custom IOutput that throws exceptions instead of calling process.exit(1) on configuration errors. The example shows a full IOutput implementation and a try/catch around replaceTscAliasPaths. ```TypeScript import { replaceTscAliasPaths, IOutput } from 'tsc-alias'; const output: IOutput = { verbose: true, debug: (message, obj) => console.debug(message, obj), info: (message) => console.log(message), error: (message, exitProcess = false) => { console.error(message); if (exitProcess) throw new Error(message); // refuse to exit the process }, clear: () => console.clear(), assert: (claim, message) => { if (!claim) throw new Error(message); } }; try { await replaceTscAliasPaths({ configFile: 'tsconfig.build.json', output }); } catch (err) { // configuration failure was raised instead of process.exit(1) console.error('build failed:', err); } ``` -------------------------------- ### Reproduce the configuration pipeline with prepareConfig Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/config-pipeline.md Imports the internal `prepareConfig` helper from `tsc-alias/dist/helpers` to load and inspect the resolved configuration. The returned `config` object exposes `output`, `baseUrl`, `inputGlob`, and `replacers`; `config.output.debug` prints the shown values. Use this to verify how `tsconfig.json`, `outDir`, `verbose`, and `resolveFullPaths` affect the pipeline. ```typescript import { prepareConfig } from 'tsc-alias/dist/helpers'; // internal module async function inspectConfig() { const config = await prepareConfig({ configFile: 'tsconfig.json', outDir: 'dist', verbose: true, resolveFullPaths: true }); config.output.debug('baseUrl:', config.baseUrl); config.output.debug('input glob:', config.inputGlob); config.output.debug('loaded replacers:', config.replacers.length); } ``` -------------------------------- ### Display tsc-alias CLI help Source: https://github.com/justkey007/tsc-alias/blob/master/README.md Shows all available CLI options for tsc-alias. ```sh tsc-alias --help ``` -------------------------------- ### prepareSingleFileReplaceTscAliasPaths(options?) Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/single-file-replacer.md Asynchronously prepares a SingleFileReplacer function. Configuration is loaded at prepare time, and the returned function can be called synchronously to replace aliases in a single file's contents. ```APIDOC ## prepareSingleFileReplaceTscAliasPaths(options?) ### Description Asynchronously prepares a SingleFileReplacer function. Configuration is loaded at prepare time, and the returned function can be called synchronously to replace aliases in a single file's contents. ### Method prepareSingleFileReplaceTscAliasPaths ### Endpoint `prepareSingleFileReplaceTscAliasPaths(options?: ReplaceTscAliasPathsOptions): Promise` ### Parameters #### Options (optional) - **options** (ReplaceTscAliasPathsOptions) - Optional - Same options as `replaceTscAliasPaths()`. `watch` and `followReferences` have no effect; `configFile`, `outDir`, `declarationDir`, `verbose`, `debug`, `resolveFullPaths`, `resolveFullExtension`, `resolvePackageSubpaths`, `replacers`, `output`, `aliasTrie`, and `fileExtensions` do. ### Return Value `Promise` - Resolves to a synchronous function that takes an input object with `fileContents` and `filePath` and returns the transformed file contents. ### Behavior Details - Calls `prepareConfig(options)` once for the main config. - If `options.declarationDir` is set and differs from `config.outPath`, prepares a second config with `outDir: declarationDir` and `declarationDir: undefined`. - Each invocation selects the active config: the declaration config is used when `filePath.endsWith('.d.ts')` or when `declarationDir` is set and `filePath.startsWith(declarationDir)`. - The returned function runs `replaceAliasString` and returns the rewritten code. ### Errors Same failure modes as `replaceTscAliasPaths` during the `prepareConfig` step (invalid/missing tsconfig, missing `outDir`): with the default `Output` they log to stderr and call `process.exit(1)`. No error is thrown for unmatched aliases — unmatched import statements are returned unchanged. ``` -------------------------------- ### Default usage inside the library Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/path-cache.md Constructs a PathCache instance per project and uses it to check alias candidates. The constructor takes options.watch, fileExtensions?.outputCheck, and configFile. The getAbsoluteAliasPath method resolves an alias candidate, and existsResolvedAlias checks if it exists. ```ts // constructed per project (src/helpers/project-config.ts:54) const pathCache = new PathCache(!options.watch, fileExtensions?.outputCheck, configFile); // used by the default replacer to check an alias candidate: const absolutePath = config.pathCache.getAbsoluteAliasPath(aliasPath.basePath, concretePath); if (config.pathCache.existsResolvedAlias(normalizePath(absolutePath))) { // candidate exists → rewrite the import to a relative path } ``` -------------------------------- ### newStringRegex Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/import-path-resolver.md Creates a regular expression for matching string literals in source code. Returns a RegExp object. ```APIDOC ## newStringRegex ### Description Creates a regular expression for matching string literals in source code. Returns a RegExp object. ### Method Function ### Signature ```ts export function newStringRegex(): RegExp; ``` ### Return Value - **RegExp** - A regular expression for matching string literals. ``` -------------------------------- ### Follow references programmatically with replaceTscAliasPaths Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/project-references.md Use replaceTscAliasPaths with followReferences: true to also run replacement in each referenced project. The configFile points to the root project with references. ```ts import { replaceTscAliasPaths } from 'tsc-alias'; await replaceTscAliasPaths({ configFile: 'tsconfig.json', // root project with "references" followReferences: true, // also run replacement in each referenced project verbose: true }); ``` -------------------------------- ### buildProjectConfig interface and function signature Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/config-pipeline.md Defines the parameters and return type for buildProjectConfig, which assembles the full configuration pipeline from loadConfig through createFinalConfig. The function returns the final config and replacers, and builds the alias trie unless options.aliasTrie is provided. ```TypeScript export interface IBuildProjectConfigParams { configFile: string; output: IOutput; options: ReplaceTscAliasPathsOptions; } export function buildProjectConfig(params: IBuildProjectConfigParams): { config: IConfig; replacers: any } ``` -------------------------------- ### Manual trie usage Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/trie.md Demonstrates adding entries with add() and searching with search(). Shows wildcard behavior: empty string prefix matches any import, longer prefixes win, and empty search returns null. ```typescript import { TrieNode } from 'tsc-alias/dist/utils/trie'; // internal module const trie = new TrieNode(); trie.add('@app/', 'alias-data-for-app'); trie.add('', 'catch-all'); // wildcard entry trie.search('@app/utils'); // 'alias-data-for-app' (longest matching prefix) trie.search('anything-else'); // 'catch-all' (fallback to empty-prefix node) trie.search(''); // null ``` -------------------------------- ### prepareSingleFileReplaceTscAliasPaths function declaration Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/single-file-replacer.md Asynchronously prepares a SingleFileReplacer. Accepts optional ReplaceTscAliasPathsOptions; watch and followReferences have no effect. Returns a Promise resolving to the synchronous replacer. ```ts /** * prepareSingleFileReplaceTscAliasPaths prepares a SingleFileReplacer. * @param {ReplaceTscAliasPathsOptions} options tsc-alias options. * @returns {Promise} a SingleFileReplacer to use for replacing aliases in a single file. */ export async function prepareSingleFileReplaceTscAliasPaths( options: ReplaceTscAliasPathsOptions = {} ): Promise ``` -------------------------------- ### Custom replacer that rewrites specifiers directly Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/replacers.md A replacer that uses newStringRegex from tsc-alias to extract the path from the import specifier. If the path starts with '@upper/', it replaces that path with its uppercase version; otherwise it returns the original string. ```ts // replacers/uppercase.cjs const { newStringRegex } = require('tsc-alias/dist/utils/import-path-resolver'); module.exports = function uppercase({ orig }) { const path = orig.match(newStringRegex())?.groups?.path; if (!path || !path.startsWith('@upper/')) return orig; return orig.replace(path, path.toUpperCase()); }; ``` -------------------------------- ### IOutput Interface Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/main.md Interface for custom output handling to intercept logging and errors. Implement this to turn configuration failures into exceptions instead of process exit. ```APIDOC ## IOutput Interface ### Description Interface for custom output handling to intercept logging and errors. Implement this to turn configuration failures into exceptions instead of process exit. ### Methods - **verbose** (boolean) - Property indicating verbose mode. - **debug(message, obj?)** - Log debug message with optional object. - **info(message)** - Log informational message. - **error(message, exitProcess?)** - Log error message; if `exitProcess` is true, the default behavior is to exit the process. Custom implementations can throw an exception instead. - **clear()** - Clear the console. - **assert(claim, message)** - Assert a condition; if false, throw an error with the message. ### Example Implementation ```ts const output: IOutput = { verbose: true, debug: (message, obj) => console.debug(message, obj), info: (message) => console.log(message), error: (message, exitProcess = false) => { console.error(message); if (exitProcess) throw new Error(message); // refuse to exit the process }, clear: () => console.clear(), assert: (claim, message) => { if (!claim) throw new Error(message); } }; ``` ``` -------------------------------- ### findResolvedAliasPath interfaces and function Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/replacers.md Helper module for the default replacer. findResolvedAliasPath iterates alias.paths, computes the concrete target, resolves an absolute candidate via config.pathCache.getAbsoluteAliasPath, and falls back to resolveExistingArtifact when the cache answer starts with '---'. Returns the first valid resolved path converted to a JS extension, or null. ```ts export interface ICheckAliasPathParams { aliasPath: AliasPath; requiredModule: string; alias: Alias; config: IConfig; } export interface IFindResolvedAliasPathParams { alias: Alias; requiredModule: string; config: IConfig; } export function findResolvedAliasPath(params: IFindResolvedAliasPathParams): string | null; ``` -------------------------------- ### applyCompilerOptions interface Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/config-pipeline.md Defines the parameters for applyCompilerOptions, which writes moduleResolution, resolves outDir with fallback to base tsconfig, applies paths with placeholder substitution, resolves baseUrl, and sets baseUrl to rootDir when paths exist without baseUrl. ```TypeScript export interface IApplyCompilerOptionsParams { config: ITSConfig; compilerOptions: any; baseTsConfig: any; configDir: string; baseConfigDir: string | null; } ``` -------------------------------- ### Regex usage for import statements and strings Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/import-path-resolver.md Shows how to use newImportStatementRegex and newStringRegex to match import/export specifiers. The first regex matches the from clause, the second captures the path and pathWithQuotes groups. Comments show the expected match results. ```ts import { newImportStatementRegex, newStringRegex } from 'tsc-alias/dist/utils/import-path-resolver'; const statement = `export { x } from "./mod.js"`; const match = statement.match(newImportStatementRegex()); // match[0] === 'from "./mod.js"' const spec = statement.match(newStringRegex()); // spec?.groups?.path === './mod.js' // spec?.groups?.pathWithQuotes === '"./mod.js"' ``` -------------------------------- ### Intercepting errors at prepare time Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/single-file-replacer.md Provides a custom IOutput object to capture errors during preparation. If the config file is invalid, the error callback throws when exitProcess is true, making the prepare call throw an exception. ```ts import { prepareSingleFileReplaceTscAliasPaths, IOutput } from 'tsc-alias'; const output: IOutput = { verbose: false, debug: () => {}, info: () => {}, clear: () => {}, error: (message, exitProcess = false) => { if (exitProcess) throw new Error(message); console.error(message); }, assert: (claim, message) => { if (!claim) throw new Error(message); } }; try { const replacer = await prepareSingleFileReplaceTscAliasPaths({ configFile: 'missing-tsconfig.json', output }); // unreachable if the config file is invalid } catch (err) { console.error('prepare failed:', err.message); } ``` -------------------------------- ### applyConfigOverrides interface Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/config-pipeline.md Defines the parameters for applyConfigOverrides, which copies fileExtensions inputGlob/outputCheck into the loaded fileExtensions object, sets output.verbose, and enables resolveFullPaths with a log message when requested. ```TypeScript export interface IApplyConfigOverridesParams { options: ReplaceTscAliasPathsOptions; output: IOutput; fileExtensions?: Partial; resolveFullPaths?: boolean; verbose?: boolean; } ``` -------------------------------- ### prepareSingleFileReplaceTscAliasPaths(options?) Source: https://github.com/justkey007/tsc-alias/blob/master/README.md Prepares a single-file replacer function. This function returns a promise that resolves to a function which can be used to transform the contents of a single file, replacing alias paths. ```APIDOC ## prepareSingleFileReplaceTscAliasPaths(options?) ### Description Prepares a single-file replacer function. This function returns a promise that resolves to a function which can be used to transform the contents of a single file, replacing alias paths. ### Method Function call (async) ### Signature ```typescript const runFile: SingleFileReplacer = await prepareSingleFileReplaceTscAliasPaths(options?); ``` ### Parameters #### options (object) - Optional Same options as `replaceTscAliasPaths`. ### Returns A promise that resolves to a `SingleFileReplacer` function. This function accepts an object with `fileContents` (string) and `filePath` (string) and returns the transformed contents (string) synchronously. ### Example ```typescript import { prepareSingleFileReplaceTscAliasPaths } from 'tsc-alias'; const runFile: SingleFileReplacer = await prepareSingleFileReplaceTscAliasPaths(options?); function treatFile(filePath: string) { const fileContents = fs.readFileSync(filePath, 'utf8'); const newContents = runFile({fileContents, filePath}); // do stuff with newContents } ``` ``` -------------------------------- ### ISetupFileWatcherParams interface Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/cli.md Defines the parameters for setupFileWatcher in src/watcher.ts. Includes config, options, globPattern, and onRestart callback. ```typescript export interface ISetupFileWatcherParams { config: IConfig; options: ReplaceTscAliasPathsOptions; globPattern: string[]; onRestart: (options: ReplaceTscAliasPathsOptions) => void; } ``` -------------------------------- ### applyTscAliasOptions interface Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/config-pipeline.md Defines the parameters for applyTscAliasOptions, which copies replacers, resolveFullPaths, resolvePackageSubpaths (only when boolean), and verbose from the tsc-alias section, defaults fileExtensions to {}, and joins pathReplacer.file onto configDir when present. ```TypeScript export interface IApplyTscAliasOptionsParams { config: ITSConfig; tscAliasConfig?: ITSCAliasConfig; configDir: string; } ``` -------------------------------- ### Typical build integration commands Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/cli.md Shows common tsc-alias usage in build pipelines. The first runs tsc then tsc-alias with a tsconfig. The second adds -f and --follow-references. The third uses --dir, -fe, --resolve-package-subpaths, and --verbose. ```sh tsc && tsc-alias -p tsconfig.json ``` ```sh tsc && tsc-alias -p tsconfig.json -f --follow-references ``` ```sh tsc && tsc-alias -p tsconfig.json --dir dist -fe .mjs --resolve-package-subpaths --verbose ``` -------------------------------- ### Output constructor signature Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/output.md Constructor for the Output class. Accepts an optional boolean or IOutputOptions object for verbose, and an optional debugMode boolean. When verbose is an object, its debug field overrides debugMode. ```ts constructor(verbose?: boolean | IOutputOptions, debugMode = false) ``` -------------------------------- ### IOutput.info Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/output.md Logs a message on the info level. This method is part of the IOutput interface that custom output options must implement. ```APIDOC ## info(message: string): void ### Description Logs a message on the info level. ### Parameters - **message** (string) - Required - The message to log. ### Returns void ``` -------------------------------- ### Output class signature and IOutputOptions interface Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/output.md Defines the IOutputOptions interface and the Output class with its constructor, properties, and methods. The class is not part of the top-level public API; it is created internally and accessed via the IOutput interface. ```ts export interface IOutputOptions { verbose?: boolean; debug?: boolean; } export class Output implements IOutput { constructor(verbose?: boolean | IOutputOptions, debugMode = false) set verbose(value: boolean): void debug: (message: string, obj?: unknown) => void info(message: string): void error(message: string, exitProcess = false): void clear(): void assert(claim: unknown, message: string): void } ``` -------------------------------- ### Use reference lookup directly with findMatchingReference and resolveReferenceTargetPath Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/project-references.md Load project references and find a matching reference for a source path, then resolve the emitted artifact path. Uses internal helpers from tsc-alias/dist/helpers/reference-path-resolver. ```ts import { findMatchingReference, resolveReferenceTargetPath } from 'tsc-alias/dist/helpers/reference-path-resolver'; // internal import { loadProjectReferences } from 'tsc-alias/dist/helpers/reference-path-resolver'; const refs = loadProjectReferences('/project/tsconfig.json'); // IProjectReferenceInfo[] const matching = findMatchingReference({ configFile: '/project/tsconfig.json', sourcePath: '/project/core/src/util.ts' }); if (matching) { const emitted = resolveReferenceTargetPath({ reference: matching, sourcePath: '/project/core/src/util.ts', fileExtensions: ['js', 'json'] }); console.log('emitted artifact:', emitted); // e.g. /project/core/dist/util.js } ``` -------------------------------- ### IOutput.assert Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/output.md Asserts a claim; when it fails, an error is logged and the process exited. This method is part of the IOutput interface that custom output options must implement. ```APIDOC ## assert(claim: unknown, message: string): void ### Description Asserts a claim; when it fails, an error is logged and the process exited. ### Parameters - **claim** (unknown) - Required - The assertion that is being claimed. - **message** (string) - Required - The message to log when the claim fails. ### Returns void ``` -------------------------------- ### Basic usage of prepareSingleFileReplaceTscAliasPaths Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/single-file-replacer.md Prepares a replacer function that rewrites alias paths in a single file's contents. Reads a file, applies the replacer, and writes back if changed. Requires a tsconfig.json file. ```ts import { readFileSync, writeFileSync } from 'fs'; import { prepareSingleFileReplaceTscAliasPaths } from 'tsc-alias'; const runFile = await prepareSingleFileReplaceTscAliasPaths({ configFile: 'tsconfig.json' }); function treatFile(filePath: string) { const fileContents = readFileSync(filePath, 'utf8'); const newContents = runFile({ fileContents, filePath }); if (newContents !== fileContents) { writeFileSync(filePath, newContents, 'utf8'); } } treatFile('dist/index.js'); ``` -------------------------------- ### Use prepareSingleFileReplaceTscAliasPaths for single file replacement Source: https://github.com/justkey007/tsc-alias/blob/master/README.md Prepare a single file replacer that transforms file contents synchronously. ```typescript import { prepareSingleFileReplaceTscAliasPaths } from 'tsc-alias'; const runFile: SingleFileReplacer = await prepareSingleFileReplaceTscAliasPaths(options?); function treatFile(filePath: string) { const fileContents = fs.readFileSync(filePath, 'utf8'); const newContents = runFile({fileContents, filePath}); // do stuff with newContents } ``` -------------------------------- ### ReplaceTscAliasPathsOptions interface Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/main.md Options object for replaceTscAliasPaths. Includes configFile, outDir, declarationDir, watch, verbose, debug, resolveFullPaths, resolveFullExtension, resolvePackageSubpaths, replacers, output, aliasTrie, fileExtensions, and followReferences. followReferences enables processing of TypeScript project references. ```typescript export interface ReplaceTscAliasPathsOptions { configFile?: string; outDir?: string; declarationDir?: string; watch?: boolean; verbose?: boolean; debug?: boolean; resolveFullPaths?: boolean; resolveFullExtension?: '.js' | '.mjs' | '.cjs'; resolvePackageSubpaths?: boolean; replacers?: string[]; output?: IOutput; aliasTrie?: TrieNode; fileExtensions?: Partial; /** * If true, tsc-alias will follow TypeScript project references defined in * tsconfig.json and run alias replacement on all referenced projects. */ followReferences?: boolean; } ``` -------------------------------- ### resolveFullImportPaths(params: IResolveFullImportPathsParams): string Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/import-path-resolver.md Rewrites every import statement in the provided code whose specifier does not already end in a runtime extension, resolving it to a full path with an extension. Returns the new code. ```APIDOC ## resolveFullImportPaths(params: IResolveFullImportPathsParams): string ### Description Rewrites every import statement in `code` whose specifier does not already end in a runtime extension, resolving it to a full path with an extension. Returns the new code. ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `code` | `string` | yes | — | Source code to scan. | | `path` | `string` | yes | — | File path of the code, used to compute the source directory. | | `ext` | `string` | no | `DEFAULT_IMPORT_EXTENSION` (`.js`) | Preferred extension appended to relative imports (`.js`, `.mjs`, `.cjs`, ...); candidates are tried in the order `[ext, '.js', '.json', '.jsx', '.cjs', '.mjs']` (deduplicated). | | `resolvePackageSubpaths` | `boolean` | no | `true` | When `true`, bare package imports (e.g. `lodash/fp`) are resolved through `node_modules`; when `false` they are left untouched. | ### Resolution Rules - If the specifier already ends with one of the runtime extensions → unchanged. - Non-relative (bare package) specifiers: unchanged unless `resolvePackageSubpaths` is `true`, in which case `resolvePackageSubpath` walks up to `node_modules` and appends the found extension (`path-to-dir/file` → `path-to-dir/file.js`). - Relative specifiers (`./x`, `../y`): `resolveExistingRuntimePath` appends the first existing extension (`x` → `x.js`) or `index.` for directories. ### Returns - `string` - The new code with resolved import paths. ### Notes This is what the CLI flag `-f/--resolve-full-paths` and the API option `resolveFullPaths: true` activate, so Node ESM (`"type": "module"`) can find emitted files without extensions. ``` -------------------------------- ### Custom IOutput to catch tsc-alias errors Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/errors.md Use a custom IOutput with throwing error and assert handlers to convert fatal errors into catchable exceptions. The error handler throws when exitProcess is true, otherwise logs; the assert handler throws on failed assertions. Wrap replaceTscAliasPaths in try/catch to catch missing tsconfig, missing outDir, or invalid file path. ```TypeScript import { replaceTscAliasPaths, IOutput } from 'tsc-alias'; const throwingOutput: IOutput = { verbose: true, debug: (message, obj?) => console.debug(message, obj), info: (message) => console.log(message), clear: () => console.clear(), error: (message, exitProcess = false) => { const err = new Error(message); if (exitProcess) throw err; // fatal → throw console.error(message); // non-fatal → just log }, assert: (claim, message) => { if (!claim) throw new Error(message); // assertion failure → throw } }; try { await replaceTscAliasPaths({ configFile: 'tsconfig.json', output: throwingOutput }); } catch (err) { // catches: missing tsconfig, missing outDir, invalid file path console.error('tsc-alias failed:', err.message); } ``` -------------------------------- ### newImportStatementRegex(flags = ''): RegExp Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/import-path-resolver.md Factory returning a regex that matches complete ESM/CommonJS import statements. Combines six alternatives to cover various import syntaxes. ```APIDOC ## `newImportStatementRegex(flags = ''): RegExp` ### Description Factory returning a regex matching complete ESM/CommonJS import statements, combining six alternatives (`src/utils/import-regex.ts`). ### Parameters - `flags` (string) - Optional - Regex flags, e.g. `'g'` for a global replace. Default: `''`. ### Returns - `RegExp` - A regex matching import statements, with alternatives for `funcStyle`, `globalStyle`, `globalMinimizedStyle`, `fromStyle`, `fromMinimizedStyle`, and `moduleStyle`. ``` -------------------------------- ### newImportStatementRegex Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/import-path-resolver.md Creates a regular expression for matching import/require statements in source code. Accepts optional flags for the RegExp. Returns a RegExp object. ```APIDOC ## newImportStatementRegex ### Description Creates a regular expression for matching import/require statements in source code. Accepts optional flags for the RegExp. Returns a RegExp object. ### Method Function ### Signature ```ts export function newImportStatementRegex(flags = ''): RegExp; ``` ### Parameters - **flags** (string) - Optional - Regular expression flags (e.g., 'g', 'i'). Default is empty string. ### Return Value - **RegExp** - A regular expression for matching import/require statements. ``` -------------------------------- ### resolveFullImportPaths Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/import-path-resolver.md Resolves full import paths in the given source code string based on the provided file path and optional extension. Returns the modified code string with resolved import paths. ```APIDOC ## resolveFullImportPaths ### Description Resolves full import paths in the given source code string based on the provided file path and optional extension. Returns the modified code string with resolved import paths. ### Method Function ### Signature ```ts export const resolveFullImportPaths: (params: IResolveFullImportPathsParams) => string; ``` ### Parameters #### Params Object - **code** (string) - Required - The source code string to process. - **path** (string) - Required - The file path used for resolution. - **ext** (string) - Optional - The file extension to use. - **resolvePackageSubpaths** (boolean) - Optional - Whether to resolve package subpaths. ### Return Value - **string** - The modified code string with resolved import paths. ``` -------------------------------- ### Wildcard pattern matching with parseWildcardPattern, matchWildcard, substituteWildcard Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/utils.md Demonstrates the internal pattern-matcher utilities. parseWildcardPattern converts a glob-like pattern into a regex, matchWildcard tests a string and returns the captured star value, and substituteWildcard replaces the star with a given value. ```typescript import { parseWildcardPattern, matchWildcard, substituteWildcard } from 'tsc-alias/dist/utils/pattern-matcher'; // internal const pattern = parseWildcardPattern('@app/*'); matchWildcard({ pattern, text: '@app/utils' }); // { matched: true, starValue: 'utils' } const indexed = parseWildcardPattern('src/*/index'); substituteWildcard({ pattern: indexed, starValue: 'x' }); // 'src/x/index' ``` -------------------------------- ### newStringRegex(): RegExp Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/import-path-resolver.md Factory returning a regex that matches a single quoted string literal with named groups. Used by replacers to extract the module specifier. ```APIDOC ## `newStringRegex(): RegExp` ### Description Factory returning a regex matching a single quoted string literal with named groups. ### Returns - `RegExp` - A regex matching a quoted string literal with named groups `pathWithQuotes` (including quotes) and `path` (specifier without quotes). ``` -------------------------------- ### IOutput interface definition Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/output.md Defines the contract for a custom output option. The library only calls these members, enabling error interception. Includes verbose, debug, info, error, clear, and assert methods. ```TypeScript export interface IOutput { /** * verbose value sets if the output should act verbose. */ verbose: boolean; /** * debug logs a message on the debug level. * @param {string} message message to log. */ debug: (message: string, obj?: unknown) => void; /** * info logs a message on the info level. * @param {string} message message to log. */ info(message: string): void; /** * error logs a message on the error level and may exit the process. * @param {string} message message to log. * @param {boolean} exitProcess if process should exit after this error. */ error(message: string, exitProcess?: boolean): void; /** * clear clears the displayed logs. */ clear(): void; /** * assert claim an assertion when it fails an error is logged * and the process exited. * @param {unknown} claim assertion that is being claimed. * @param {string} message message to log when claim fails. */ assert(claim: unknown, message: string): void; } ``` -------------------------------- ### TrieNode constructor Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/trie.md Initializes children = new Map() and data = null. ```typescript constructor() ``` -------------------------------- ### Resolve full paths for ESM output Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/import-path-resolver.md Uses resolveFullImportPaths to append the .js extension to relative and package subpath imports. The output comments show expected transformations when the target files exist. Requires the internal import-path-resolver module. ```ts import { resolveFullImportPaths } from 'tsc-alias/dist/utils/import-path-resolver'; // internal const code = `import { b } from '../utils/helper'; import { a } from 'lodash/fp';`; const out = resolveFullImportPaths({ code, path: '/project/dist/index.js', ext: '.js', resolvePackageSubpaths: true }); // '../utils/helper' → '../utils/helper.js' (if helper.js exists) // 'lodash/fp' → 'lodash/fp.js' (if lodash/fp.js exists in node_modules) ``` -------------------------------- ### Rewrite every import in a file with a custom replacer Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/import-path-resolver.md Uses replaceSourceImportPaths and newStringRegex from the internal import-path-resolver module. The AliasReplacer callback receives an object with orig, file, and config; here it uppercases the matched path. The config argument is passed as undefined as any. ```ts import { replaceSourceImportPaths, newStringRegex } from 'tsc-alias/dist/utils/import-path-resolver'; // internal import { AliasReplacer } from 'tsc-alias'; const code = `import { a } from "@app/a"; const b = require("@app/b");`; const quoteUpper: AliasReplacer = ({ orig }) => { const path = orig.match(newStringRegex())?.groups?.path; return path ? orig.replace(path, path.toUpperCase()) : orig; }; const rewritten = replaceSourceImportPaths(code, '/src/index.ts', (orig) => quoteUpper({ orig, file: '/src/index.ts', config: undefined as any })); ``` -------------------------------- ### Path extension conversion with convertDTSPathToJsExtension, removeJavascriptExtension, normalizePathExtension Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/utils.md Shows how to convert .d.ts/.d.mts paths to .js/.mjs, strip the .js extension, and normalize a .ts path to .js. Useful for resolving import paths after compilation. ```typescript import { convertDTSPathToJsExtension, removeJavascriptExtension, normalizePathExtension } from 'tsc-alias/dist/utils/alias-path-normalizer'; convertDTSPathToJsExtension('dist/a.d.ts'); // 'dist/a.js' convertDTSPathToJsExtension('dist/a.d.mts'); // 'dist/a.mjs' removeJavascriptExtension('dist/a.js'); // 'dist/a' normalizePathExtension('dist/a.ts'); // 'dist/a.js' ``` -------------------------------- ### Add tsc-alias to build scripts in package.json (alternative) Source: https://github.com/justkey007/tsc-alias/blob/master/README.md Adds build and build:watch scripts that run tsc and tsc-alias, with watch mode using concurrently. ```json "scripts": { "build": "tsc && tsc-alias", "build:watch": "tsc && (concurrently \"tsc -w\" \"tsc-alias -w\")" } ``` -------------------------------- ### replaceSourceImportPaths Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/import-path-resolver.md Replaces import/require specifiers in the given source code string using a custom replacer function. Returns the modified code string. ```APIDOC ## replaceSourceImportPaths ### Description Replaces import/require specifiers in the given source code string using a custom replacer function. Returns the modified code string. ### Method Function ### Signature ```ts export const replaceSourceImportPaths: (code: string, path: string, replacer: StringReplacer) => string; ``` ### Parameters - **code** (string) - Required - The source code string to process. - **path** (string) - Required - The file path used for context. - **replacer** (StringReplacer) - Required - A function that takes an import statement and returns the replacement string. ### Return Value - **string** - The modified code string with replaced import paths. ``` -------------------------------- ### IOutput.debug Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/output.md Logs a message on the debug level. This method is part of the IOutput interface that custom output options must implement. ```APIDOC ## debug(message: string, obj?: unknown): void ### Description Logs a message on the debug level. ### Parameters - **message** (string) - Required - The message to log. - **obj** (unknown) - Optional - Additional object to log. ### Returns void ``` -------------------------------- ### Watch mode: replaceTscAliasPaths({ watch: true }) Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/main.md Rewrites newly added/changed files and restarts on tsconfig change. Typically wired into a build script as "build:watch": "tsc && (concurrently \"tsc -w\" \"tsc-alias -w\")". ```TypeScript import { replaceTscAliasPaths } from 'tsc-alias'; // rewrites newly added/changed files and restarts on tsconfig change await replaceTscAliasPaths({ watch: true }); ``` -------------------------------- ### Constants in src/utils/constants.ts Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/utils.md Defines default file extensions, runtime extensions, preferred import extension, and scoped package prefix used by tsc-alias. ```ts export const DEFAULT_FILE_EXTENSIONS = ['js', 'json', 'jsx', 'cjs', 'mjs', 'd.ts', 'd.tsx', 'd.cts', 'd.mts'] as const; export const DEFAULT_RUNTIME_EXTENSIONS = DEFAULT_FILE_EXTENSIONS.filter( (extension) => !extension.startsWith('d.') ).map((extension) => `.${extension}`); export const DEFAULT_IMPORT_EXTENSION = DEFAULT_RUNTIME_EXTENSIONS[0]; export const SCOPED_PACKAGE_PREFIX = '@'; ``` -------------------------------- ### IReadConfigReferencesParams interface Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/project-references.md Defines the parameters for reading the 'references' field from a tsconfig file. The function returns absolute paths of each referenced project's tsconfig.json and logs debug messages for missing references or files. ```typescript export interface IReadConfigReferencesParams { configFile: string; output?: IOutput; } ``` -------------------------------- ### SingleFileReplacer type definition Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/single-file-replacer.md Defines the synchronous function signature returned by prepareSingleFileReplaceTscAliasPaths. The input object requires fileContents and filePath; filePath selects the active config and computes relative paths. ```ts export type SingleFileReplacer = (input: { fileContents: string; filePath: string }) => string; ```