reduce size of node_modules for production

Hari Prasath picture Hari Prasath · May 9, 2017 · Viewed 9.3k times · Source

I created node_modules for uploading addon to online site from localhost with help of ngrok and using npm install in CommandPrompt. But the created node_modules folder size was 78mb. In that case i must reduce the size by removing the unwanted folders, so I surfed the internet and got two suggestions, as it could be efficient to get size reduced, they are: using --production mode and the other is using shrinkwrap.

As first step I used the command npm install --production and npm install --only=production as specified here: How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?, but I din't see any change in folder size.

Then referred on how to use shrinkwrap to reduce size as given in this site and tried it: https://docs.npmjs.com/cli/shrinkwrap, but it did not success.

Additionally I referred here : https://www.npmjs.com/package/modclean, where using the command modclean -n default:safe I got 10-11mb reduced.

But, still I have a large number of unwanted folders in node_modules. I have specified few needed dependencies in package.json as follows,

"dependencies": {
    "atlassian-connect-express": "2.0.0",
    "body-parser": "^1.14.2",
    "compression": "^1.6.0",
    "cookie-parser": "^1.4.0",
    "errorhandler": "^1.4.2",
    "express": "^4.13.3",
    "express-hbs": "*",
    "jugglingdb-sqlite3": "0.0.5",
    "morgan": "^1.6.1",
    "static-expiry": ">=0.0.5"
}

The dependencies I have given in package.json is few, but I see a large sets of folders created in node_modules. How can I reduce the size of node_modules, is there any other process?

Answer

Joe Clay picture Joe Clay · May 9, 2017

As of NPM v3, all of the dependencies in your app are, where possible, kept in the top level of your node_modules - this makes it easier for NPM to remove duplicates, and prevents some nasty 'path too long' errors on Windows.

The important thing to realize is that when I say 'all of the dependencies in your app', I don't just mean the ones in your package.json - all of those packages will have their own dependencies too (and their dependencies might have dependencies of their own, and so on). This is why node_modules always has so many folders inside.

As an example - express has 28 dependencies, so that'd be a minimum of 29 folders in your node_modules if that was the only thing you'd installed - and that's without factoring in sub-dependencies.

So, to answer your question - aside from the things you specified, you can't make your node_modules any smaller, because you are using all of those folders! Just not always in the most direct way.