Use Nx Named Inputs to Reuse Glob Patterns Across Inputs

Share this video with your friends

Send Tweet
Published 5 months ago
Updated a month ago

Sometimes you might want to use a pattern you defined for a certain input in a different one somewhere else in your nx.json confg.

You can do that by defining a namedInputs object field and setting your named input's name as the key, and the glob pattern as the value.

Instructor: [0:00] Being able to specify these inputs and give Nx some hints about what the cache should include and what it shouldn't, is a real powerful way to fine-tune and improve your cache hits. [0:11] You can even combine those with multiple patterns, for instance, say you want to exclude all markdown files but for the build target, a real-world scenario would also be to exclude all spec files because we don't really want to rerun the build every time a spec file changes.

[0:26] Now, over time, you might notice that you might duplicate these patterns because we don't just have the build target, but potentially, we might have test target, for instance, for which we might want to have a similar setup where we also want to ignore the markdown files.

[0:42] For this purpose in Nx, you can have something like named inputs, which is a dedicated section where you can name your glow patterns. For instance, we can use this inputs here and give it a name. In this case, we could say no markdown. Now, instead of actually specifying these patterns down here, we could go and say noMarkdown.

[1:02] NX will automatically recognize that this is a named input and it would just replace it basically with the glob pattern that you specified up here. This has the same effect. If we run npx nx build shared UI, it would run the build because we change nx.jason. If we run it again, it reads it from the cache.

[1:25] If we change the readme of our shared UI, let's say we add a couple of exclamation marks and rerun the built, it still pulls it out of the cache because we excluded the readme explicitly with this pattern here. We can even go further.

[1:40] If it's part of building shared UI, some charge dependOns are being built as well, we might want to exclude marked on changes on those two. And so, we can go here and specify that by adding this sign in front.

[1:54] This indicates NX that it should not only exclude the markdown files off the project on which we triggered the build, but also charge projects that are being triggered as part of building, in this case, shared UI.