UNPKG

@reliverse/rse

Version:

@reliverse/rse is your all-in-one companion for bootstrapping and improving any kind of projects (especially web apps built with frameworks like Next.js) — whether you're kicking off something new or upgrading an existing app. It is also a little AI-power

67 lines (66 loc) 2.24 kB
import path from "@reliverse/pathkit"; import fs from "@reliverse/relifso"; import { relinka } from "@reliverse/relinka"; import { glob } from "tinyglobby"; async function detectCurrentImportSymbol(projectPath) { const commonSymbols = ["@", "~", "#", "$", "@src", "@app"]; const files = await glob("**/*.{js,jsx,ts,tsx}", { cwd: path.resolve(projectPath) }); const symbolCounts = /* @__PURE__ */ new Map(); for (const file of files) { const filePath = path.join(projectPath, file); const content = await fs.readFile(filePath, "utf-8"); for (const symbol of commonSymbols) { const importRegex = new RegExp(`(from|import)\\s+(['"])${symbol}/`, "g"); const matches = content.match(importRegex); if (matches) { symbolCounts.set( symbol, (symbolCounts.get(symbol) ?? 0) + matches.length ); } } } let mostUsedSymbol = null; let maxCount = 0; symbolCounts.forEach((count, symbol) => { if (count > maxCount) { maxCount = count; mostUsedSymbol = symbol; } }); return mostUsedSymbol; } export async function replaceImportSymbol(projectPath, toSymbol) { const fromSymbol = await detectCurrentImportSymbol(projectPath); if (!fromSymbol) { relinka( "warn", "No common import symbol detected in the project. No changes will be made." ); return; } relinka( "info", `Replacing import symbol "${fromSymbol}" with "${toSymbol}" in ${projectPath}` ); const files = await glob("**/*.{js,jsx,ts,tsx}", { cwd: path.resolve(projectPath) }); for (const file of files) { const filePath = path.join(projectPath, file); const content = await fs.readFile(filePath, "utf-8"); const updatedContent = content.replace( new RegExp(`from (['"])${fromSymbol}([^'"]*?)\\1`, "g"), (_match, quote, path2) => `from ${quote}${toSymbol}${path2}${quote}` ).replace( new RegExp(`import (['"])${fromSymbol}([^'"]*?)\\1`, "g"), (_match, quote, path2) => `import ${quote}${toSymbol}${path2}${quote}` ); if (content !== updatedContent) { await fs.writeFile(filePath, updatedContent, "utf-8"); relinka("info", `Updated imports in ${filePath}`); } } }