Previous Lecture Complete and continue  

  Separating Development and Production Dependencies

Update Jul 15, 2017: npm v5 is faster than npm v4, for more details read change log or watch my video.

Second item on our agenda, separating development and production dependencies. The rule of thumb is that the fewer dependencies you have, especially the ones that you don't really need, the better. Because having extra dependencies, it's not just increasing your payload that you want to deploy, but it also exposes you and your obligation to extra risks and vulnerabilities. So the separation of dependencies, one of the best practices in Node.js.

That's why the Node.js manifest file, package.json, supports three types of dependencies: One is dependencies. Another is devDependencies. And then, there is also optionalDependencies. Most of the time, you don't need to use optionalDependencies. But you just absolutely must put any dependencies which you don't need in production, you must put them in devDependencies. You can do it manually, or when you install, you can provide -D flag or --save-dev flag. In this example, I'm using webpack and I'm bundling all my front-end files in a bundled.js. So that's why I don't need babel-core. I don't need axios because I'm using it just on the front end. And of course, I don't need node-dev in production.

When you're running npm install, npm install will read from package.json or npm shrinkwrap. And then it will install two types of dependencies. So basically all dependencies will be installed, the regular ones and the devDependencies. With npm install production, which is --production flag, only the regular dependencies will be installed. You can use npm prune with the flag production. That will clear the devDependencies. It's okay to use that on your local development machine.

But I recommend just completely removing node_modules using rm -rf node_modules, and then using npm install --production. This is the cleaner way because npm is not very deterministic. It depends. The actual tree structure of the dependencies will be resolved based on the order in which you install those dependencies. So, it's just cleaner, safer to just completely get rid of that node_modules folder and install everything with the production flag. That's exactly how the code will be run in production or in your CI/CD pipeline. So, this is what I recommend.