### Complex Configuration Example with tsconfig.json Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/prepareConfig.md This example illustrates a comprehensive configuration setup using both tsconfig.json and tsc-alias specific settings. It shows how to define compiler options, alias paths, and detailed configurations for verbose logging, full path resolution, and custom replacers. The prepareConfig function then loads these settings to create a fully prepared configuration object. ```json // tsconfig.json { "compilerOptions": { "baseUrl": "src", "outDir": "dist", "paths": { "@app/*": ["app/*"], "@utils/*": ["../shared/utils/*"], "@api": ["../api-service"] } }, "tsc-alias": { "verbose": true, "resolveFullPaths": true, "replacers": { "default": { "enabled": true }, "base-url": { "enabled": true }, "custom": { "enabled": true, "file": "./my-replacer.js" } }, "fileExtensions": { "inputGlob": "{js,jsx,mjs}", "outputCheck": ["js", "json", "jsx", "mjs"] } } } // Usage const config = await prepareConfig({ configFile: './tsconfig.json' }); // config now has all settings from tsconfig + replacers loaded ``` -------------------------------- ### PathLike Example Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/types.md Demonstrates how to define alias patterns and their corresponding path resolutions using the PathLike type. This example shows common alias setups like '@app/*', '@utils', and '@api'. ```typescript const paths: PathLike = { '@app/*': ['src/app/*'], '@utils': ['src/utils'], '@api': ['../api-service'] }; ``` -------------------------------- ### Example ReplacerOptions Configuration Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/types.md An example demonstrating how to configure replacers. It shows enabling default and base-url replacers, and a custom replacer loaded from a specific file. ```typescript const replacers: ReplacerOptions = { 'default': { enabled: true }, 'base-url': { enabled: true }, 'custom-replacer': { enabled: true, file: './replacers/custom.js' } }; ``` -------------------------------- ### Basic Setup with Logging Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/Output.md Demonstrates how to instantiate the Output class and use its logging methods for basic information and debugging. ```APIDOC ## Example: Basic Logging ### Description Instantiate `Output` with verbose and debug enabled, then use `info` and `debug` methods. ### Code ```typescript import { Output } from 'tsc-alias'; const output = new Output(true, true); // verbose + debug enabled output.info('Starting alias replacement'); output.debug('Configuration loaded', { baseUrl: 'src' }); output.info('2 files affected'); ``` ``` -------------------------------- ### tsconfig.json Configuration Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/README.md Example configuration for tsconfig.json demonstrating baseUrl, outDir, and paths for alias mapping. ```json { "compilerOptions": { "baseUrl": "src", "outDir": "dist", "paths": { "@app/*": ["app/*"], "@utils/*": ["utils/*"] } } } ``` -------------------------------- ### Debug Output Example: Already Resolved Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/baseUrlReplacer.md An example of debug output indicating that the module required by the base URL replacer has already been resolved. ```text tsc-alias debug: base-url replacer - requiredModule: utils/helpers tsc-alias debug: base-url replacer - already resolved ``` -------------------------------- ### PathLike Example Usage Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/TrieNode.md Demonstrates the structure of the PathLike type with sample alias and path patterns. ```typescript const paths: PathLike = { '@app/*': ['src/app/*'], '@utils': ['src/utils'], '@lib/*': ['../shared/lib/*'] }; ``` -------------------------------- ### Debug Output Example: Resolved Import Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/baseUrlReplacer.md An example of debug output when the base URL replacer successfully resolves an import and determines the relative path. ```text tsc-alias debug: base-url replacer - requiredModule: utils/helpers tsc-alias debug: base-url replacer - relativePath: ../../utils tsc-alias debug: base-url replacer - newImportScript: import { x } from '../../utils' ``` -------------------------------- ### Absolute Output Directory Configuration Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/loadConfig.md Example tsconfig.json with a relative baseUrl and an absolute outDir. The absolute outDir is used directly. ```json { "compilerOptions": { "baseUrl": "src", "outDir": "/absolute/path/dist" } } ``` -------------------------------- ### Basic Output Setup Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/Output.md Instantiate the Output class with verbose and debug logging enabled. Use info and debug methods to log messages and object details during operation. ```typescript import { Output } from 'tsc-alias'; const output = new Output(true, true); // verbose + debug enabled output.info('Starting alias replacement'); output.debug('Configuration loaded', { baseUrl: 'src' }); output.info('2 files affected'); ``` -------------------------------- ### Relative Output Directory Configuration Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/loadConfig.md Example tsconfig.json with a relative baseUrl and outDir. Paths are resolved relative to the project root. ```json { "compilerOptions": { "baseUrl": "src", "outDir": "dist" } } ``` -------------------------------- ### Simple Alias Replacement Example Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/defaultReplacer.md Shows how an import from an aliased path is transformed into a relative path after compilation. This is useful for understanding how module resolution works with path aliases. ```json { "compilerOptions": { "baseUrl": "src", "outDir": "dist", "paths": { "@utils/*": ["utils/*"] } } } ``` ```javascript import { helper } from '@utils/helpers'; ``` ```javascript import { helper } from '../../utils/helpers'; ``` -------------------------------- ### Prepare Configuration Object Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/prepareConfig.md This example demonstrates how to use prepareConfig to load and validate configuration options. It shows basic usage with a specified tsconfig file, verbose logging, and full path resolution. The resulting config object's properties like baseUrl, outDir, aliasTrie, and replacers are then logged. ```typescript import { prepareConfig } from 'tsc-alias'; import { replaceTscAliasPaths } from 'tsc-alias'; // Used internally by replaceTscAliasPaths const config = await prepareConfig({ configFile: './tsconfig.json', verbose: true, resolveFullPaths: true }); console.log('Base URL:', config.baseUrl); console.log('Output directory:', config.outDir); console.log('Aliases loaded:', config.aliasTrie); console.log('Active replacers:', config.replacers.length); ``` -------------------------------- ### Config Mutation Example Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/importReplacers.md Demonstrates how the `importReplacers` function modifies the `config` object in place by populating its `replacers` array. ```typescript config.replacers = []; // Initially empty await importReplacers(config, replacerOptions, cmdReplacers); // config.replacers now populated with loaded functions ``` -------------------------------- ### Install tsc-alias Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/README.md Install tsc-alias as a development dependency using npm. ```bash npm install --save-dev tsc-alias ``` -------------------------------- ### Relative Path Aliases Configuration Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/loadConfig.md Example tsconfig.json demonstrating relative path aliases. These paths are preserved and resolved later based on file locations. ```json { "compilerOptions": { "baseUrl": "src", "paths": { "@parent/*": ["../other-dir/*"] } } } ``` -------------------------------- ### Monorepo tsconfig.json Configuration Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/configuration.md A tsconfig.json example tailored for monorepo structures, defining paths across different packages. ```json { "compilerOptions": { "baseUrl": "packages/core/src", "outDir": "packages/core/dist", "paths": { "@core/*": ["*"], "@shared/*": ["../../shared/src/*"], "@utils/*": ["../../packages/utils/src/*"] } }, "tsc-alias": { "verbose": false, "resolveFullPaths": true } } ``` -------------------------------- ### Replacer Execution Order Example Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/importReplacers.md Demonstrates how multiple replacers are applied sequentially, with the output of one serving as the input for the next. This chaining allows for complex import transformations. ```typescript config.replacers.forEach((replacer) => { code = replaceSourceImportPaths(code, file, (orig) => replacer({ orig, file, config }) ); }); ``` ```typescript // replacers = [default, base-url, custom] // Original: import x from '@utils/helpers' // After default: import x from '../../utils/helpers' // After base-url: (no change, already relative) // After custom: (custom checks for 'helpers' pattern) ``` -------------------------------- ### Watch Mode Setup in package.json Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/configuration.md Configures scripts in package.json to enable watch mode for both TypeScript compilation and tsc-alias. ```json { "scripts": { "build": "tsc && tsc-alias", "dev": "concurrently \"tsc -w\" \"tsc-alias -w\"" } } ``` -------------------------------- ### tsc-alias Section Configuration Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/loadConfig.md Example structure for the optional `tsc-alias` section within tsconfig.json, showing available configuration options. ```json { "tsc-alias": { "verbose": boolean, "resolveFullPaths": boolean, "fileExtensions": { "inputGlob": string, "outputCheck": string[] }, "replacers": { "[name]": { "enabled": boolean, "file": string } } } } ``` -------------------------------- ### Processing Multiple Files with Shared Configuration Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/replaceAliasString.md Iterate over multiple files, applying the same alias replacement configuration to each. This example uses `glob` to find files and `fs` to read/write content, demonstrating a common build pipeline step. ```typescript import { prepareConfig, replaceAliasString } from 'tsc-alias'; import fs from 'fs'; import glob from 'glob'; const config = await prepareConfig({ configFile: './tsconfig.json', resolveFullPaths: true }); const files = glob.sync('dist/**/*.js'); for (const file of files) { const original = fs.readFileSync(file, 'utf8'); const transformed = replaceAliasString(config, file, original, true, '.js'); if (original !== transformed) { fs.writeFileSync(file, transformed, 'utf8'); console.log(`Updated: ${file}`); } } ``` -------------------------------- ### Basic Configuration Loading with loadConfig Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/loadConfig.md Loads a tsconfig.json file using the loadConfig function and logs its properties. Ensure the 'tsc-alias' package is installed. ```typescript import { loadConfig } from 'tsc-alias'; import { Output } from 'tsc-alias'; const output = new Output(true, true); const config = loadConfig('/project/tsconfig.json', output); console.log('Base URL:', config.baseUrl); console.log('Output Dir:', config.outDir); console.log('Paths:', config.paths); ``` -------------------------------- ### CLI Usage Examples Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/README.md Execute tsc-alias from the command line after TypeScript compilation. Supports watch mode and custom tsconfig files. ```bash # After TypeScript compilation tsc && tsc-alias # With watch mode tsc-alias -w # Custom tsconfig tsc-alias -p ./config/tsconfig.json ``` -------------------------------- ### Default Replacer Debug Output Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/defaultReplacer.md Example debug output from the default replacer, showing the resolution of an alias to its absolute path and the generated import statement. ```text tsc-alias debug: default replacer - requiredModule: @utils/helpers tsc-alias debug: default replacer - alias: { prefix: '@utils', ... } tsc-alias debug: default replacer - absoluteAliasPath: /project/src/utils/helpers tsc-alias debug: default replacer - relativeAliasPath: ../../utils/helpers tsc-alias debug: default replacer - newImportScript: import { x } from '../../utils/helpers' ``` -------------------------------- ### Batch File Processing with replaceAlias Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/replaceAlias.md Shows how to process multiple JavaScript files in a directory using replaceAlias in conjunction with glob. This example enables full path resolution. ```typescript import { replaceAlias, prepareConfig } from 'tsc-alias'; import glob from 'glob'; const config = await prepareConfig({ configFile: './tsconfig.json', resolveFullPaths: true }); const files = glob.sync('dist/**/*.js'); let modifiedCount = 0; for (const file of files) { const changed = await replaceAlias( config, file, true, '.js' ); if (changed) modifiedCount++; } console.log(`Modified ${modifiedCount} files`); ``` -------------------------------- ### prepareConfig Function Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/prepareConfig.md Loads, validates, and prepares a complete configuration object for tsc-alias operations. It handles config file resolution, loading, path setup, alias trie building, and replacer loading. ```APIDOC ## prepareConfig ### Description Loads, validates, and prepares a complete configuration object for tsc-alias operations. This function is essential for setting up the environment for alias replacement. ### Signature ```typescript async function prepareConfig( options: ReplaceTscAliasPathsOptions ): Promise ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **options** (`ReplaceTscAliasPathsOptions`) - Required - Options object specifying config file path, behavior overrides, and replacers. ### Request Example ```typescript import { prepareConfig } from 'tsc-alias'; const config = await prepareConfig({ configFile: './tsconfig.json', verbose: true, resolveFullPaths: true }); ``` ### Response #### Success Response (200) `IConfig` - A complete configuration object with all paths resolved, aliases built, and replacers loaded. This includes: - `configFile` (string): Absolute path to tsconfig.json - `baseUrl` (string): Base URL for path resolution from tsconfig - `outDir` (string): Output directory from tsconfig - `configDir` (string): Directory containing tsconfig.json - `outPath` (string): Resolved output path - `confDirParentFolderName` (string): Parent directory name of config directory - `hasExtraModule` (boolean): True if project has external module references - `configDirInOutPath` (string | null): Path to config directory within outDir - `relConfDirPathInOutPath` (string | null): Relative path from outDir to config directory - `pathCache` (PathCache): Cache for file existence checks - `inputGlob` (string): Glob pattern for finding compiled files - `output` (object): Logger instance - `aliasTrie` (TrieNode): Prefix tree of aliases for matching - `replacers` (AliasReplacer[]): Array of replacement functions #### Response Example ```json { "configFile": "/path/to/your/project/tsconfig.json", "baseUrl": "src", "outDir": "dist", "configDir": "/path/to/your/project", "outPath": "/path/to/your/project/dist", "confDirParentFolderName": "your_project", "hasExtraModule": false, "configDirInOutPath": null, "relConfDirPathInOutPath": null, "pathCache": {}, "inputGlob": "**/*.{js,jsx,mjs}", "output": {}, "aliasTrie": {}, "replacers": [] } ``` ### Error Handling - **Config file not found**: Process exits with code 1 and error message. - **`outDir` not in tsconfig.json**: Process exits with code 1 with assertion error. - **Invalid replacer module**: Logs error but continues with remaining replacers. ``` -------------------------------- ### Install tsc-alias as Dev Dependency Source: https://github.com/justkey007/tsc-alias/blob/master/README.md Install tsc-alias as a development dependency in your project. This makes it available for project-specific build scripts. ```sh npm install --save-dev tsc-alias ``` -------------------------------- ### Install tsc-alias Globally Source: https://github.com/justkey007/tsc-alias/blob/master/README.md Install tsc-alias globally for command-line usage. This command is typically run once per development environment. ```sh npm install -g tsc-alias ``` -------------------------------- ### Loading Built-in Replacers with prepareConfig Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/importReplacers.md Demonstrates how to prepare configuration and load built-in replacers automatically. The `config.replacers` will contain default and baseUrl replacers. ```typescript import { importReplacers, prepareConfig } from 'tsc-alias'; const config = await prepareConfig({ configFile: './tsconfig.json' }); // replacers are loaded automatically during prepareConfig // config.replacers now contains [defaultReplacer, baseUrlReplacer] ``` -------------------------------- ### Example Custom AliasReplacer Function Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/types.md An example of how to implement a custom AliasReplacer. This replacer checks if the original import statement includes '@custom' and transforms it accordingly, otherwise returning the original statement. ```typescript const customReplacer: AliasReplacer = ({ orig, file, config }) => { // If import contains @custom, transform it if (orig.includes('@custom')) { return orig.replace('@custom', './custom-path'); } return orig; // Return unchanged if no match }; ``` -------------------------------- ### Loading Custom Replacers via CLI Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/importReplacers.md Demonstrates how to specify custom replacer files directly on the command line using the -r flag. ```bash tsc-alias -r ./replacers/custom1.js ./replacers/custom2.js ``` -------------------------------- ### File Resolution Logic Explanation Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/importPathResolver.md Illustrates the step-by-step logic applied when resolving a relative import path. It prioritizes adding the extension directly, then checks for an index file within a directory, and falls back to leaving the import unchanged if no match is found. ```text Given: import x from './foo' 1. Check if './foo.js' exists → use './foo.js' 2. Check if './foo/index.js' exists → use './foo/index.js' 3. Otherwise → leave as './foo' ``` -------------------------------- ### Already Resolved Import (Not Changed) Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/baseUrlReplacer.md Imports that already start with '.' are considered relative and are not modified by the base URL replacer. ```javascript import { x } from './utils/helpers'; ``` -------------------------------- ### Using Custom Output with replaceTscAliasPaths Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/Output.md Shows how to create a custom Output instance and pass it to the `replaceTscAliasPaths` function to control logging behavior. ```APIDOC ## Example: Custom Output with replaceTscAliasPaths ### Description Create a custom `Output` instance and provide it to `replaceTscAliasPaths` to manage logging during the alias replacement process. ### Code ```typescript import { replaceTscAliasPaths, Output } from 'tsc-alias'; const customOutput = new Output(true, false); await replaceTscAliasPaths({ configFile: './tsconfig.json', output: customOutput }); // Uses customOutput for all logging ``` ``` -------------------------------- ### prepareConfig() Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/INDEX.md Loads and validates the tsc-alias configuration. ```APIDOC ## prepareConfig() ### Description Load and validate configuration. ### Purpose Handles the loading and validation of configuration settings for tsc-alias. ``` -------------------------------- ### Initialize Output Class Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/Output.md Instantiate the Output class, optionally enabling verbose or debug logging modes. ```typescript class Output implements IOutput { constructor(verbose?: boolean, debugMode?: boolean) } ``` -------------------------------- ### Manual Trie Construction and Search Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/TrieNode.md Shows how to manually construct a TrieNode and add entries. Demonstrates searching for exact and prefix matches. ```typescript const trie = new TrieNode(); // Add some entries trie.add('app', 'src/app'); trie.add('apple', 'src/apple'); trie.add('app/utils', 'src/app/utils'); trie.search('app'); // Returns 'src/app' trie.search('apple'); // Returns 'src/apple' trie.search('app/utils'); // Returns 'src/app/utils' trie.search('app/other'); // Returns 'src/app' (prefix match) trie.search('other'); // Returns null ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/configuration.md Run tsc-alias with the default tsconfig.json file. ```bash tsc-alias ``` -------------------------------- ### Disabling Default Replacers in tsconfig.json Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/importReplacers.md Configuration example showing how to disable the built-in 'default' and 'base-url' replacers while enabling a custom replacer. ```json { "compilerOptions": { ... }, "tsc-alias": { "replacers": { "default": { "enabled": false }, "base-url": { "enabled": false }, "custom": { "enabled": true, "file": "./my-replacer.js" } } } } ``` -------------------------------- ### Custom Replacer Module Format Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/importReplacers.md Example of a custom replacer module exporting a default function that transforms import statements based on specific conditions. ```typescript // ./my-replacer.js export default function myReplacer({ orig, file, config }) { // Transform the import statement if (orig.includes('@custom')) { return orig.replace('@custom', './custom-path'); } return orig; // Return unchanged if no match } ``` -------------------------------- ### Enable Watch Mode Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/configuration.md Use the -w or --watch flag to enable watch mode, which recompiles files as they change. ```bash tsc-alias -w ``` -------------------------------- ### Import Statement Detection Examples Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/replaceAliasString.md Illustrates the various types of import statements that the `replaceSourceImportPaths` function is designed to detect and process, including CommonJS and ES Module syntax. ```javascript // CommonJS require const module = require('some/path'); const asyncModule = await import('some/path'); // ES Module import import module from 'some/path'; import theDefault, {namedExport} from 'some/path'; import 'some/path'; export * from 'some/path'; ``` -------------------------------- ### Output Class Constructor Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/Output.md Initializes a new instance of the Output class. It accepts optional boolean flags to enable verbose logging and debug mode. ```APIDOC ## Constructor Initializes a new instance of the Output class. ### Parameters #### Constructor Parameters - **verbose** (boolean) - Optional - Default: `false` - Enable verbose-level logging (info messages print to console). - **debugMode** (boolean) - Optional - Default: `false` - Enable debug-level logging. When enabled, adds a debug function that logs with inspection. ``` -------------------------------- ### Enable Verbose Logging Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/configuration.md Use the -v or --verbose flag to enable verbose logging for detailed output. ```bash tsc-alias -v ``` -------------------------------- ### Advanced: Custom Processing Pipeline with Single File Replacer Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/prepareSingleFileReplaceTscAliasPaths.md Demonstrates using the prepared replacer within a custom file processing loop, such as in a build framework. It reads files, applies replacements, and writes back only if changes occurred. ```typescript // Advanced: Custom processing pipeline const replacer = await prepareSingleFileReplaceTscAliasPaths({ configFile: 'config/tsconfig.json', verbose: true }); // Process in custom framework function processDistribution(outputDir) { for (const file of fs.readdirSync(outputDir)) { if (!file.endsWith('.js')) continue; const filePath = path.join(outputDir, file); const original = fs.readFileSync(filePath, 'utf8'); const replaced = replacer({ fileContents: original, filePath }); if (original !== replaced) { fs.writeFileSync(filePath, replaced, 'utf8'); console.log(`Updated: ${file}`); } } } ``` -------------------------------- ### prepareSingleFileReplaceTscAliasPaths() Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/INDEX.md Prepares a reusable replacer function for processing a single file. ```APIDOC ## prepareSingleFileReplaceTscAliasPaths() ### Description Prepare reusable single-file replacer. ### Purpose Creates a function that can be used to replace aliases in a single file, without direct I/O operations. ``` -------------------------------- ### Basic File Processing with replaceAlias Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/replaceAlias.md Demonstrates how to use replaceAlias to process a single JavaScript file. Ensure you have prepared the configuration using prepareConfig beforehand. ```typescript import { replaceAlias, prepareConfig } from 'tsc-alias'; const config = await prepareConfig({ configFile: './tsconfig.json', verbose: true }); const changed = await replaceAlias(config, 'dist/module.js'); if (changed) { console.log('File was modified'); } else { console.log('No changes needed'); } ``` -------------------------------- ### PathCache for Alias Resolution Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/PathCache.md Use PathCache to resolve an alias to its absolute path. The `getAbsoluteAliasPath` method checks the cache for performance. It returns a string starting with '---' if the alias is not found. ```typescript const cache = new PathCache(true); // Resolve where an alias points to const aliasPath = cache.getAbsoluteAliasPath( '/project/dist', '@utils/helpers' ); if (aliasPath.startsWith('---')) { console.log('Alias path not found, using fallback'); } else { console.log(`Alias resolves to: ${aliasPath}`); } ``` -------------------------------- ### Output Class Constructor and Methods Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/Output.md The Output class can be instantiated with optional verbose and debug flags. It provides methods for logging information, debugging messages, handling errors, clearing the console, and asserting conditions. ```APIDOC ## Class: Output ### Description Implements the `IOutput` interface for logging within tsc-alias. ### Methods - **constructor(verbose?: boolean, debug?: boolean)**: Initializes the Output class. `verbose` and `debug` flags control the verbosity of the output. - **debug(message: string, obj?: unknown): void**: Logs a debug message. Optionally includes an object for more detailed information. - **info(message: string): void**: Logs an informational message. - **error(message: string, exitProcess?: boolean): void**: Logs an error message. If `exitProcess` is true, the process will exit after logging. - **clear(): void**: Clears the console output. - **assert(claim: unknown, message: string): void**: Asserts a condition. If the `claim` is falsy, an error message is logged. ``` -------------------------------- ### Add tsc-alias to package.json Build Scripts (Alternative) Source: https://github.com/justkey007/tsc-alias/blob/master/README.md An alternative configuration for package.json build scripts. This setup uses tsc-alias in conjunction with concurrently for watching both tsc and tsc-alias during development. ```json "scripts": { "build": "tsc && tsc-alias", "build:watch": "tsc && (concurrently "tsc -w" "tsc-alias -w")" } ``` -------------------------------- ### Specify tsconfig.json Path Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/configuration.md Use the -p or --project flag to specify a custom path to the tsconfig.json file. ```bash tsc-alias -p ./config/tsconfig.json ``` -------------------------------- ### Replacer File Search Order Example Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/importReplacers.md Illustrates the order in which tsc-alias searches for custom replacer files when a relative path is provided. It checks the current working directory first, then node_modules. ```typescript // When loading replacer from "./replacers/my-replacer.js" // 1. Check: ${cwd}/replacers/my-replacer.js // 2. Check: ${cwd}/node_modules/replacers/my-replacer.js // 3. Error if not found ``` -------------------------------- ### Configure Full Path Resolution Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/configuration.md Use the -f or --resolve-full-paths flag to resolve incomplete imports to full paths, and -fe or --resolve-full-extension to specify the file extension for resolved paths. Supports .js, .mjs, and .cjs. ```bash tsc-alias -f -fe .mjs ``` -------------------------------- ### Custom Special Import Replacer Logic Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/importReplacers.md This JavaScript function intercepts import paths and transforms those starting with '@special/' into relative paths. It's designed to be used with tsc-alias's custom replacer feature. ```typescript export default function specialReplacer({ orig, file, config }) { // Match @special/* patterns if (orig.includes('@special')) { const path = orig.match(/'([^']+)'/)[1]; if (path.startsWith('@special/')) { const relativePath = `./${path.replace('@special/', '')}`; return orig.replace(path, relativePath); } } return orig; } ``` -------------------------------- ### Customizing File Extension Handling Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/configuration.md Override the default glob pattern for input files and the list of output file extensions to check. This is useful for projects with non-standard file types or build processes. ```json { "fileExtensions": { "inputGlob": "{js,jsx,mjs,cjs}", "outputCheck": ["js", "json", "jsx", "cjs", "mjs", "d.ts", "d.tsx"] } } ``` -------------------------------- ### Alias Replacement with Full Path Resolution Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/replaceAliasString.md Enable `resolveFullPaths: true` in `prepareConfig` to append file extensions during alias replacement. This is useful for environments that require explicit file extensions. ```typescript const config = await prepareConfig({ configFile: './tsconfig.json', resolveFullPaths: true }); const sourceCode = ` import { helper } from './utils/helper'; import Button from '@components/Button'; `; const transformed = replaceAliasString( config, 'dist/pages/index.js', sourceCode, true, '.js' ); // transformed: // import { helper } from './utils/helper.js'; // import Button from '../../components/Button.js'; ``` -------------------------------- ### Add tsc-alias to package.json Build Scripts Source: https://github.com/justkey007/tsc-alias/blob/master/README.md Integrate tsc-alias into your project's build process by adding it to the 'scripts' section of your package.json. This example shows a common build command that first compiles with tsc and then runs tsc-alias. ```json "scripts": { "build": "tsc --project tsconfig.json && tsc-alias -p tsconfig.json" } ``` -------------------------------- ### Configure tsc-alias via tsconfig.json Source: https://github.com/justkey007/tsc-alias/blob/master/README.md Configure tsc-alias settings directly within your tsconfig.json file under the 'tsc-alias' key. This example demonstrates enabling verbose output, resolving full paths, and configuring custom replacers and file extensions. ```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"] } } } ``` -------------------------------- ### Prepare and Use Single File Replacer with tsc-alias Source: https://github.com/justkey007/tsc-alias/blob/master/README.md Use `prepareSingleFileReplaceTscAliasPaths` to get a function that transforms file contents. Pass the same options as `replaceTscAliasPaths`. The returned replacer function takes an object with `fileContents` and `filePath` and returns the modified content. ```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 } ``` -------------------------------- ### Error Handling for Replacer Preparation Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/prepareSingleFileReplaceTscAliasPaths.md Shows how to catch configuration errors when preparing the replacer function. The returned replacer itself is synchronous and does not throw errors for invalid imports. ```typescript try { const replacer = await prepareSingleFileReplaceTscAliasPaths({ configFile: 'invalid-path.json' }); } catch (error) { // Catches configuration errors (missing file, invalid config) console.error('Failed to prepare replacer:', error.message); } ``` -------------------------------- ### Multiple Target Paths for an Alias Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/defaultReplacer.md Illustrates how the replacer attempts each target path defined for an alias in order, using the first one that exists. This allows for fallback or alternative locations for modules. ```json { "compilerOptions": { "paths": { "@app/*": ["src/app/*", "dist/legacy/app/*"] } } } ``` -------------------------------- ### loadConfig() Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/INDEX.md Parses the tsconfig.json file to load configuration. ```APIDOC ## loadConfig() ### Description Parse tsconfig.json file. ### Purpose Parses the tsconfig.json file to extract relevant configuration options. ``` -------------------------------- ### Loading Custom Replacers after prepareConfig Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/importReplacers.md Illustrates the state of `config.replacers` after loading custom replacers defined in tsconfig.json. ```typescript const config = await prepareConfig({ configFile: './tsconfig.json' }); // config.replacers = [defaultReplacer, baseUrlReplacer, customReplacer] ``` -------------------------------- ### Error Handling and Assertions Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/Output.md Illustrates how to use the `error` method for conditional error reporting with process exit, and the `assert` method for validating conditions. ```APIDOC ## Example: Error Handling and Assertions ### Description Demonstrates using `output.error` to log errors and optionally exit the process, and `output.assert` to validate conditions. ### Code ```typescript const output = new Output(); // Conditional error with process exit const configPath = getConfigPath(); if (!fs.existsSync(configPath)) { output.error(`Configuration not found: ${configPath}`, true); } // Using assert for validation output.assert( config.outDir !== undefined, 'compilerOptions.outDir is required' ); ``` ``` -------------------------------- ### Error Handling and Assertions Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/Output.md Demonstrates conditional error logging with an option to exit the process if a critical configuration is missing. Also shows how to use the assert method for runtime validation of conditions. ```typescript const output = new Output(); // Conditional error with process exit const configPath = getConfigPath(); if (!fs.existsSync(configPath)) { output.error(`Configuration not found: ${configPath}`, true); } // Using assert for validation output.assert( config.outDir !== undefined, 'compilerOptions.outDir is required' ); ``` -------------------------------- ### Chaining Replacer Functions Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/replaceAliasString.md Demonstrates how the configuration's replacers are chained together, passing the output of one replacer as the input to the next. This is used to sequentially modify import paths. ```typescript config.replacers.forEach((replacer) => { code = replaceSourceImportPaths(code, file, (orig) => replacer({ orig, file, config }) ); }); ``` -------------------------------- ### Placeholder Replacement in tsconfig.json Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/loadConfig.md Demonstrates how placeholders like ${configDir} in tsconfig.json paths are replaced with actual directory values. ```typescript // Input: { "compilerOptions": { "baseUrl": "src", "paths": { "@config": ["${configDir}/config"] } } } // Result: // If configDir is "/project", the path becomes "/project/config" ``` -------------------------------- ### Executing Custom Replacers from CLI Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/importReplacers.md Shows the programmatic way to trigger the replacement process with custom replacers specified via an array of file paths. ```typescript await replaceTscAliasPaths({ replacers: ['./replacers/custom1.js', './replacers/custom2.js'] }); ``` -------------------------------- ### Override Input Glob Patterns and Output Extensions Check Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/configuration.md Use --inputglob to specify custom glob patterns for input files and --outputcheck to override the default extensions checked for output files. ```bash tsc-alias --inputglob "{js,jsx}" --outputcheck js json jsx ``` -------------------------------- ### Handle File I/O Errors with replaceAlias Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/replaceAlias.md Demonstrates how to catch and handle specific file system errors (ENOENT, EACCES) that may occur during alias replacement. Ensure the config object is prepared before calling replaceAlias. ```typescript try { const changed = await replaceAlias(config, 'dist/missing.js'); } catch (error) { if (error.code === 'ENOENT') { console.error('File not found'); } else if (error.code === 'EACCES') { console.error('Permission denied'); } else { console.error('Unexpected error:', error.message); } } ``` -------------------------------- ### loadConfig() Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/README.md Parses the tsconfig.json file to load project-specific TypeScript configuration, which is essential for understanding path aliases. ```APIDOC ## loadConfig() ### Description Parse tsconfig.json. ### Method (Not specified, likely a function call in a Node.js environment) ### Endpoint (Not applicable, this is a library function) ### Parameters (Refer to `api-reference/loadConfig.md` for detailed parameter information) ### Request Example (Refer to `api-reference/loadConfig.md` for example usage) ### Response (Refer to `api-reference/loadConfig.md` for response details) ``` -------------------------------- ### TrieNode constructor and add method Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/TrieNode.md Manually constructs a TrieNode and adds entries to it. This allows for custom trie structures. ```APIDOC ## TrieNode constructor and add method ### Description Manually constructs a TrieNode and adds entries to it. This allows for custom trie structures to be built programmatically. ### Constructor `new TrieNode()` ### Method: add Adds a key-value pair to the trie. #### Method Signature `trie.add(key: string, value: T): void` ### Parameters #### Path Parameters - **key** (string) - Required - The key to add to the trie. - **value** (T) - Required - The value associated with the key. ### Usage Examples ```typescript const trie = new TrieNode(); // Add some entries trie.add('app', 'src/app'); trie.add('apple', 'src/apple'); trie.add('app/utils', 'src/app/utils'); // Searching after adding entries trie.search('app'); // Returns 'src/app' trie.search('apple'); // Returns 'src/apple' trie.search('app/utils'); // Returns 'src/app/utils' trie.search('app/other'); // Returns 'src/app' (prefix match) trie.search('other'); // Returns null ``` ``` -------------------------------- ### PathCache Integration for Default Replacer Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/defaultReplacer.md Demonstrates how the default replacer utilizes PathCache to check for resolved aliases. The first call checks the filesystem, while subsequent calls leverage the cache for improved performance. ```typescript // First call checks filesystem const exists1 = config.pathCache.existsResolvedAlias('/path/to/file'); // Subsequent calls use cache const exists2 = config.pathCache.existsResolvedAlias('/path/to/file'); ``` -------------------------------- ### resolveFullImportPaths() Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/README.md Resolves incomplete import paths to their full, absolute paths, ensuring correct module resolution. ```APIDOC ## resolveFullImportPaths() ### Description Resolve incomplete import paths. ### Method (Not specified, likely a function call in a Node.js environment) ### Endpoint (Not applicable, this is a library function) ### Parameters (Refer to `api-reference/importPathResolver.md#resolvefullimportpaths` for detailed parameter information) ### Request Example (Refer to `api-reference/importPathResolver.md#resolvefullimportpaths` for example usage) ### Response (Refer to `api-reference/importPathResolver.md#resolvefullimportpaths` for response details) ``` -------------------------------- ### resolveFullImportPaths() Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/INDEX.md Adds file extensions to incomplete import paths. ```APIDOC ## resolveFullImportPaths() ### Description Add extensions to incomplete imports. ### Purpose Resolves and completes import paths by adding necessary file extensions. ``` -------------------------------- ### Basic Usage of replaceTscAliasPaths Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/api-reference/replaceTscAliasPaths.md Use this snippet for basic path replacement with default settings, assuming tsconfig.json is in the current directory. ```typescript import { replaceTscAliasPaths } from 'tsc-alias'; // Basic usage with defaults (tsconfig.json in current directory) await replaceTscAliasPaths(); ``` -------------------------------- ### importReplacers() Source: https://github.com/justkey007/tsc-alias/blob/master/_autodocs/INDEX.md Loads replacer modules dynamically. ```APIDOC ## importReplacers() ### Description Load replacer modules. ### Purpose Dynamically loads external modules that provide custom alias replacement logic. ```