Configure Nx Caching

Share this video with your friends

Send Tweet
Published 4 months ago
Updated 6 hours ago

It's a waste of computation resources to run your build scripts if there haven't been any changes.

Nx's caching features save you time and resources. Get started by just running the nx init command and then setting the scripts you want to cache in the generated nx.json

Instructor: [0:00] One of the great strengths of Annex is its ability to cache your computation. To cache your build test, link, runs, whatever you configure. For instance, right now, if we run something like Annex build shared UI, it would run the build. If we run it again, it still runs the computation again, even though we didn't change anything in our project. [0:21] This is obviously a waste of computational resources and also a waste of energy, if you want. In order to get caching going, let's create a small Annex Json file and specify what operations we want to cache. Now we can just create an Annex Json file manually or we can run the Annex init command, which will automatically create such Annex Json file for us.

[0:43] What you can see here, it just adds the bare minimum. It adds that task runner options, which is the default one, and then it has a cache operations. By default, cache operations is empty because it's very specific to your workspace.

[0:58] Now one could argue that probably build and test and lint are some of the most commonly used commands. Most of the time, those would be a good fit. For instance, if we go to my remix-app/package.json, there is a dev command. We probably don't want it to cache the dev command, because Jest's just hitting it, serving up the local development server of remix. In our case, build would be the best fit.

[1:22] Let's add build, which is the one that all of the products have and the one that we want to actually cache. Now, having configured that, let's try again and run the build command for shared UI. Obviously, the first time it would run but at this point, we would have it cached and so if we rerun, it would be immediate.

[1:42] In fact, you can see now it took just eight milliseconds to run it. There's also small note down here which mentions that Nx read the output from the cache for the one out of one tasks. Obviously, this works also with the run menu command.

[1:55] If you run again the command for all the products in our workspace, now in this case, what we would see is that one would be cached, which is our shared UI because we had that executed just a second ago. The remix command, we didn't run yet. This one would be executed automatically.

[2:14] Again, the note down here mentions that one out of the two tasks that have been executed has been pulled out of the cache. Also, if you rerun this, now both of them would be pulled out of the cache. You can see that clearly in the speed of the execution.