DEV Community

Fu Cheng
Fu Cheng

Posted on

Clear Nx Cache

Nx cache can be cleared by removing files in the directory node_modules/.cache/nx.

Sometimes, you have to clear cache. For example, if you moved a component to another library, the component was still kept in the cache of the old library. This may break builds.

Top comments (2)

Collapse
 
cloudromb profile image
CloudROMB

We have implemented this solution in our project:

package.json

  "scripts": {
    "nx": "nx",
    "postnx": "node checkAndClearCache.js",
...
Enter fullscreen mode Exit fullscreen mode

checkAndClearCache.js

const fs = require('fs');
const rimraf = require('rimraf');
const getSize = require('get-folder-size');

const cachePath = 'node_modules/.cache/nx';
const maxCacheMb = 2048;

if (fs.existsSync(cachePath)) {
  getSize(cachePath, (err, size) => {
    if (err) {
      throw err;
    }

    const MBSize = (size / 1024 / 1024).toFixed(2);

    console.log(`*** NX cache size is ${MBSize} Megabytes`);
    if (MBSize > maxCacheMb) {
      console.log('*** CLEAR NX CACHE ***');
      rimraf.sync(cachePath);
    }
  });
}
Enter fullscreen mode Exit fullscreen mode
Collapse
 
sebastiandg7 profile image
Sebastián Duque G

You can also use the --skip-nx-cache flag :)