Skip to content

Instantly share code, notes, and snippets.

@WomB0ComB0
Created March 22, 2025 03:38
Show Gist options
  • Save WomB0ComB0/67ec3f26997fdc360ba7b4fe9cbb61af to your computer and use it in GitHub Desktop.
Save WomB0ComB0/67ec3f26997fdc360ba7b4fe9cbb61af to your computer and use it in GitHub Desktop.
remove-duplicate-packages.ts and related files - with AI-generated descriptions
import fs from 'node:fs';
import path from 'node:path';
import type { PackageJson } from 'type-fest';
const packageJsonPath = path.join(process.cwd(), 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')) as PackageJson;
const dependencies =
packageJson.dependencies ||
(() => {
throw new Error('No dependencies found');
})();
const devDependencies =
packageJson.devDependencies ||
(() => {
throw new Error('No dev dependencies found');
})();
const picked = {
...Object.entries(dependencies)
.filter(([key, _]) => {
return !devDependencies[key];
})
.map(([key, value]) => {
return [key, value];
})
.reduce(
(acc, [key, value]) => {
if (
!key ||
!value ||
acc[key]
) return acc;
acc[key] = value;
return acc;
},
{} as Record<string, string>,
),
};
if (require.main === module) {
(async () => {
try {
packageJson.dependencies = picked;
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
} catch (error) {
console.error(`${error instanceof Error ? error.message : error}`);
} finally {
process.exit(0);
}
})();
}

remove-duplicate-packages.ts Description

File Type: ts

Generated Description:

remove-duplicate-packages.ts Analysis

Summary

This TypeScript script removes duplicate package entries from a package.json file. Specifically, it identifies packages listed in both dependencies and devDependencies and removes them from the dependencies section, leaving them only in devDependencies. It then overwrites the original package.json file with the updated dependencies. The script handles cases where either dependencies or devDependencies are missing and exits gracefully with a status code of 0 even if errors occur.

Key Components and Functions

  1. packageJsonPath: Determines the path to the package.json file using process.cwd() to get the current working directory.

  2. packageJson: Reads and parses the package.json file into a PackageJson object (presumably a type definition from type-fest). It uses error handling to throw if neither dependencies nor devDependencies are found.

  3. dependencies and devDependencies: Extracts the dependencies and devDependencies objects from the parsed packageJson. Includes error handling for missing dependency sections.

  4. picked: This is the core logic. It uses a series of chained array methods:

    • Object.entries: Converts the dependencies object into an array of key-value pairs.
    • .filter: Filters out entries where the key also exists in devDependencies.
    • .map: (Redundant in this case, could be removed) Creates a new array with the same key-value pairs.
    • .reduce: Creates a new object ({} as Record<string, string>) containing only the unique dependencies (those not present in devDependencies). It includes a check for null or undefined keys and values and avoids overwriting existing entries.
  5. if (require.main === module): This check ensures the code inside the async function only executes when the script is run directly (not imported as a module).

  6. async function: This function handles the file writing. It updates packageJson.dependencies with the picked object, writes the modified JSON back to the file using fs.writeFileSync, and includes a try...catch...finally block for robust error handling.

Notable Patterns and Techniques

  • Error Handling: The script uses try...catch blocks to handle potential errors during file reading and writing, and it throws custom errors if dependencies are missing, ensuring graceful failure and informative error messages.
  • Immutability (Partial): While it modifies the packageJson object directly, the core logic in picked uses functional programming techniques (filter, reduce, map) to build a new object based on the original dependencies without directly mutating it.
  • Type Safety (Partial): Uses TypeScript for type checking, leveraging type-fest for better type definitions. This improves code maintainability and helps prevent errors.
  • Functional Programming Paradigm: The use of filter, map, and reduce demonstrates the functional approach to data manipulation.

Potential Use Cases

  • Maintaining Clean package.json Files: This script helps automate the process of removing redundant dependencies, leading to cleaner and more manageable project files.
  • Pre-Deployment Script: This could be included as part of a pre-deployment workflow to ensure the production package.json contains only necessary dependencies.
  • Improving Build Performance: Redundant dependencies might cause unnecessary build time or consume more space during packaging. Removing duplicates can potentially optimize build performance.
  • Code Consistency: Enforcing a single location for each dependency improves code consistency and maintainability.

This script is a valuable tool for maintaining clean and efficient Node.js projects. However, it’s important to note that manually reviewing the resulting package.json is always recommended before deploying to production.

Description generated on 3/21/2025, 11:38:57 PM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment