remove_path_alias_by_tsmorph
Replace path aliases (e.g., '@/') with relative paths in import/export statements within a specified directory or file. Uses ts-morph to analyze tsconfig.json and resolve aliases. Optionally preview changes with a dry run.
Instructions
[Uses ts-morph] Replaces path aliases (e.g., '@/') with relative paths in import/export statements within the specified target path.
Analyzes the project based on tsconfig.json to resolve aliases and calculate relative paths.
Usage
Use this tool to convert alias paths like import Button from '@/components/Button' to relative paths like import Button from '../../components/Button'. This can be useful for improving portability or adhering to specific project conventions.
Specify the absolute path to the project
tsconfig.json.Specify the absolute path to the target file or directory where path aliases should be removed.
Optionally, run with
dryRun: trueto preview the changes without modifying files.
Parameters
tsconfigPath (string, required): Absolute path to the project
tsconfig.jsonfile. Must be an absolute path.targetPath (string, required): The absolute path to the file or directory to process. Must be an absolute path.
dryRun (boolean, optional): If true, only show intended changes without modifying files. Defaults to false.
Result
On success: Returns a message containing the list of file paths modified (or scheduled to be modified if dryRun).
On failure: Returns a message indicating the error.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| dryRun | No | If true, only show intended changes without modifying files. | |
| targetPath | Yes | Absolute path to the target file or directory. | |
| tsconfigPath | Yes | Absolute path to the project's tsconfig.json file. |
Implementation Reference
- Core implementation of the path alias removal logic using ts-morph. Processes target files or directories, identifies import/export declarations with path aliases, resolves them, and replaces with relative paths.export async function removePathAlias({ project, targetPath, dryRun = false, baseUrl, paths, }: { project: Project; // Project インスタンスは呼び出し元で作成・管理 targetPath: string; dryRun?: boolean; baseUrl: string; paths: Record<string, string[]>; }): Promise<{ changedFiles: string[] }> { let filesToProcess: SourceFile[] = []; const directory = project.getDirectory(targetPath); if (directory) { filesToProcess = directory.getSourceFiles("**/*.{ts,tsx,js,jsx}"); } else { const sourceFile = project.getSourceFile(targetPath); if (!sourceFile) { throw new Error( `指定されたパスはプロジェクト内でディレクトリまたはソースファイルとして見つかりません: ${targetPath}`, ); } filesToProcess.push(sourceFile); } const changedFilePaths: string[] = []; for (const sourceFile of filesToProcess) { const modified = processSourceFile(sourceFile, baseUrl, paths, dryRun); if (!modified) { continue; } changedFilePaths.push(sourceFile.getFilePath()); } return { changedFiles: changedFilePaths }; }
- src/mcp/tools/register-remove-path-alias-tool.ts:9-106 (registration)Registers the 'remove_path_alias_by_tsmorph' MCP tool with schema and handler that wraps the core removePathAlias function.server.tool( "remove_path_alias_by_tsmorph", `[Uses ts-morph] Replaces path aliases (e.g., '@/') with relative paths in import/export statements within the specified target path. Analyzes the project based on \`tsconfig.json\` to resolve aliases and calculate relative paths. ## Usage Use this tool to convert alias paths like \`import Button from '@/components/Button'\` to relative paths like \`import Button from '../../components/Button'\`. This can be useful for improving portability or adhering to specific project conventions. 1. Specify the **absolute path** to the project\`tsconfig.json\`. 2. Specify the **absolute path** to the target file or directory where path aliases should be removed. 3. Optionally, run with \`dryRun: true\` to preview the changes without modifying files. ## Parameters - tsconfigPath (string, required): Absolute path to the project\`tsconfig.json\` file. **Must be an absolute path.** - targetPath (string, required): The absolute path to the file or directory to process. **Must be an absolute path.** - dryRun (boolean, optional): If true, only show intended changes without modifying files. Defaults to false. ## Result - On success: Returns a message containing the list of file paths modified (or scheduled to be modified if dryRun). - On failure: Returns a message indicating the error.`, { tsconfigPath: z .string() .describe("Absolute path to the project's tsconfig.json file."), targetPath: z .string() .describe("Absolute path to the target file or directory."), dryRun: z .boolean() .optional() .default(false) .describe( "If true, only show intended changes without modifying files.", ), }, async (args) => { const startTime = performance.now(); let message = ""; let isError = false; let duration = "0.00"; const project = new Project({ tsConfigFilePath: args.tsconfigPath, }); try { const { tsconfigPath, targetPath, dryRun } = args; const compilerOptions = project.compilerOptions.get(); const tsconfigDir = path.dirname(tsconfigPath); const baseUrl = path.resolve( tsconfigDir, compilerOptions.baseUrl ?? ".", ); const pathsOption = compilerOptions.paths ?? {}; const result = await removePathAlias({ project, targetPath, dryRun, baseUrl, paths: pathsOption, }); if (!dryRun) { await project.save(); } const changedFilesList = result.changedFiles.length > 0 ? result.changedFiles.join("\n - ") : "(No changes)"; const actionVerb = dryRun ? "scheduled for modification" : "modified"; message = `Path alias removal (${ dryRun ? "Dry run" : "Execute" }): Within the specified path '${targetPath}', the following files were ${actionVerb}:\n - ${changedFilesList}`; } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error); message = `Error during path alias removal process: ${errorMessage}`; isError = true; } finally { const endTime = performance.now(); duration = ((endTime - startTime) / 1000).toFixed(2); } const finalMessage = `${message}\nStatus: ${ isError ? "Failure" : "Success" }\nProcessing time: ${duration} seconds`; return { content: [{ type: "text", text: finalMessage }], isError: isError, }; }, );
- Zod schema defining input parameters: tsconfigPath, targetPath, dryRun.{ tsconfigPath: z .string() .describe("Absolute path to the project's tsconfig.json file."), targetPath: z .string() .describe("Absolute path to the target file or directory."), dryRun: z .boolean() .optional() .default(false) .describe( "If true, only show intended changes without modifying files.", ), },
- Helper function that processes a single source file: scans import/export declarations, replaces path aliases with relative paths if applicable.function processSourceFile( sourceFile: SourceFile, baseUrl: string, paths: Record<string, string[]>, dryRun: boolean, ): boolean { let changed = false; const sourceFilePath = sourceFile.getFilePath(); const alias = Object.keys(paths); const declarations: (ImportDeclaration | ExportDeclaration)[] = [ ...sourceFile.getImportDeclarations(), ...sourceFile.getExportDeclarations(), ]; for (const declaration of declarations) { const moduleSpecifierNode = declaration.getModuleSpecifier(); if (!moduleSpecifierNode) continue; const moduleSpecifier = moduleSpecifierNode.getLiteralText(); if (!isPathAlias(moduleSpecifier, alias)) { continue; } // TypeScript/ts-morph の解決結果を使用 const resolvedSourceFile = declaration.getModuleSpecifierSourceFile(); if (!resolvedSourceFile) { // console.warn(`[remove-path-alias] Could not resolve module specifier: ${moduleSpecifier} in ${sourceFilePath}`); continue; // 解決できないエイリアスはスキップ } const targetAbsolutePath = resolvedSourceFile.getFilePath(); const relativePath = calculateRelativePath( sourceFilePath, targetAbsolutePath, { simplifyIndex: false, removeExtensions: true, }, ); if (!dryRun) { declaration.setModuleSpecifier(relativePath); } changed = true; } return changed; }
- Helper function to check if a module specifier matches any path alias from tsconfig paths.function isPathAlias(moduleSpecifier: string, alias: string[]): boolean { // paths のキー(例: "@/*", "@components/*", "exact-alias")に基づいて判定 return alias.some((alias) => { if (moduleSpecifier === alias) { return true; // 完全一致 } if (!alias.endsWith("/*")) { return false; // ワイルドカードエイリアスでない場合は false } const prefix = alias.substring(0, alias.length - 1); // 末尾の '*' を除く (例: "@/", "@components/") return moduleSpecifier.startsWith(prefix); }); }