简体   繁体   中英

Is there a way of cleaning a node_modules directory leaving only the required dependent files?

Installing and managing packages using npm is great! What I don't find so great is the mess it can leave.

I've started using npm for both client and node dependency management and I've noticed lots of different arrangements for the various packages I rely on. Some have lib folders, some have src folders, some dist , some docs , some examples Etc. I understand that this is because generally these packages come directly from source.

My question is:

Is there a way of identifying or even automating the removal of any unneeded files, for deployment to production? I'm thinking: removal of any readme.md (easy enough I guess) or example files (probably easy enough).

Ideally I'd like to be able to calculate exactly what the dependency tree looks like from my entry point and delete unneeded / unused files ... This is obviously a lot harder for client packages that rely on images or fonts or HTML for example.

EDIT:

As pointed out by Alexander Mac (below) A good strategy for front-end dep's is to include client dependencies as dev-dependencies and build. So my question is only related to nodejs apps.

I might suggest building your code (and deps) into one bundle with rollup.js or webpack2 .

These module loaders leverage tree-shaking approach to include only the code that is actually used.

You can run: npm prune which will remove modules from ./node_modules not specified as dependencies in packages.json.

npm dedupe will remove duplicate dependencies by pulling equivalent modules up to the root ./node_modules/. I don't know how useful this is though. I did it and then realised there were a whole bunch of modules I was using indirectly which I could also use directly, so there's that.

A surefire way of doing this is also:

rm -rf ./node_modules ./bower_components npm install

It's good practice to do a clean build before release to production anyway.

Also, I use sinopia to cache modules locally, which relieves network traffic, so these re-installs are a bit less time intensive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM