DEV Community

Teodor Dermendzhiev
Teodor Dermendzhiev

Posted on

Shrinking `node_modules`: Strategies to Reclaim Your Disk Space

The node_modules directory is notorious for gobbling up disk space in JavaScript projects. If left unchecked, it can quickly balloon in size, consuming valuable storage. Here are seven strategies to keep it lean and free up disk space:

1. Embrace npm ci for Clean Installs:

  • When setting up a project from an existing package-lock.json, use npm ci. It removes the existing node_modules and installs dependencies afresh, ensuring no lingering, unnecessary packages occupy space.

2. Prune Redundant Packages:

  • Over time, you might accumulate packages that are no longer in use. After removing a package from package.json, run npm prune to ensure it and its orphaned dependencies are purged from node_modules.

3. Limit Global Installations:

  • While global installations can be convenient for CLI tools, be judicious. Only install packages globally that you use across projects to avoid multiple space-consuming installations.

4. Visualize and Audit with npm list:

  • Use npm list to get an overview of your dependencies. Spotting and removing unnecessary large packages can free up significant space.

5. Deduplicate with npm dedupe:

  • Redundant or duplicated packages can bloat node_modules. Run npm dedupe to consolidate and reduce the directory's size by eliminating these redundancies.

6. Exclude from Version Control:

  • Committing node_modules to version control not only bloats the repository but also your local clone. Always use a .gitignore file to keep node_modules out of version control.

7. Regularly Update and Clean Cache:

  • Keeping dependencies updated can sometimes reduce their size due to optimizations. Additionally, clear the npm cache periodically using npm cache clean --force to free up space taken by outdated or unused packages.

Conclusion:
The node_modules directory, while essential, doesn't have to be a disk space hog. By implementing these strategies, you can maintain a lean project environment, ensuring efficient use of storage and a smoother development experience.

Top comments (1)

Collapse
 
dasheck0 profile image
Stefan Neidig

I discovered npkill a while back and use it regularly now. Very easy to reclaim disk space. Especially for projects that you only visit infrequently.