Dependency Pruning for Production
In this lesson, you will learn how to shrink your deployment artifacts by distinguishing between tools needed for building your application and the code required to actually run it.
When you install packages in Node.js, your node_modules folder often becomes bloated with utilities you only need during development—like testing frameworks (e.g., jest), linters (e.g., eslint), or build tools (e.g., typescript). If you bundle all these into your production server, you increase your deployment size, lengthen your CI/CD build times, and expand your security attack surface.
The Power of devDependencies
The solution is to categorize your dependencies in your package.json file. When you add a package, you choose whether it belongs in dependencies (needed at runtime) or devDependencies (needed only during development).
{
"dependencies": {
"express": "^4.18.2"
},
"devDependencies": {
"jest": "^29.5.0",
"eslint": "^8.40.0"
}
}
By explicitly separating these, you gain the ability to "prune" the development tools before shipping your code to production.
Automating the Prune
When your CI/CD pipeline prepares your project for production, you should use the --production flag with your package manager. This tells Node.js to ignore the devDependencies block entirely:
# Using npm
npm install --production
# Using yarn
yarn install --production
When this command runs, the package manager looks at your package.json, identifies the items under dependencies, and installs only those. Any existing devDependencies currently in your node_modules folder will be removed.
By pruning your dependencies, you ensure that your production environment remains lean, fast to deploy, and focused only on the code that powers your application. This is a critical step in maintaining a clean and secure production deployment.
Key Takeaway: Always categorize your packages into dependencies and devDependencies so you can use the --production flag to discard unnecessary build tools before deployment.