node-linker-pro
Version:
Keep node_modules out of cloud sync folders by linking them to a local cache. Cross-platform. Includes global npm setup command.
59 lines (46 loc) • 2.01 kB
JavaScript
import fsp from "fs/promises";
import path from "path";
import chalk from "chalk";
const projectDir = process.cwd();
const pkgPath = path.join(projectDir, "package.json");
async function init() {
console.log(chalk.blue("Configuring project for node-linker-pro..."));
let pkgContent;
let pkgData;
try {
pkgContent = await fsp.readFile(pkgPath, "utf-8");
pkgData = JSON.parse(pkgContent);
} catch (err) {
console.error(chalk.red("Error: No `package.json` found in the current directory."));
console.error(chalk.yellow("Please run this command from the root of your project."));
process.exit(1);
}
// Ensure scripts object exists
if (!pkgData.scripts) {
pkgData.scripts = {};
}
const preinstallCommand = "node-linker-pro";
if (pkgData.scripts.preinstall === preinstallCommand) {
console.log(chalk.green("✅ Project is already configured."));
console.log(`You can now run ${chalk.cyan("npm install")} as usual.`);
return;
}
if (pkgData.scripts.preinstall) {
console.error(chalk.red("Error: A `preinstall` script already exists in your package.json."));
console.error(chalk.yellow("Please manually add `node-linker-pro` to your existing preinstall script."));
console.error(`Current preinstall: "${pkgData.scripts.preinstall}"`);
process.exit(1);
}
pkgData.scripts.preinstall = preinstallCommand;
// Preserve original formatting (indentation)
const indent = pkgContent.match(/^(\s*)"/m)?.[1] || " ";
const newPkgContent = JSON.stringify(pkgData, null, indent);
await fsp.writeFile(pkgPath, newPkgContent);
console.log(chalk.green("✅ Success! Added `preinstall` script to your package.json."));
console.log(chalk.bold(`\nNow, just run ${chalk.cyan("npm install")} to link and install your dependencies.`));
}
init().catch(err => {
console.error(chalk.red("An unexpected error occurred:"), err);
process.exit(1);
});