Test Affected Projects
One of the key features of Nx in a monorepo setting is that you’re able to run tasks only for projects that are actually affected by the code changes that you’ve made. This feature relies on git
to determine which files have been changed.
If we were developing locally, you could commit your changes so far and then make a small change to the products
library.
import styles from './products.module.css';
export function Products() { return ( <div className={styles['container']}> <h1>Welcome to Products!</h1> <p>This is a change. 👋</p> </div> );}
export default Products;
Then the following command would run the tests for only the projects affected by this change:
# This does not work in the browser webcontainernx affected -t test
Use this command in the webcontainer terminal to manually specify which files have been touched.
nx affected -t test --files=libs/products/src/lib/products.tsx
Note that the unit tests were run for products
, react-store
and inventory
, but not for orders
because a change to products
can not possibly break the tests for orders
. In a small repo like this, there isn’t a lot of time saved, but as there are more tests and more projects, this quickly becomes an essential command.
You can also see what projects are affected in the graph visualizer with;
nx graph --affected --files=libs/products/src/lib/products.tsx
Build the Apps for Deployment
If you’re ready and want to ship your applications, you can build them using
nx run-many -t build
All the required files will be placed in /apps/react-store/dist
and /apps/inventory/dist
and can be deployed to your favorite hosting provider.
Nx will run any script defined in package.json
, so you can create a deploy
task that sends the build output to your hosting provider.
{ "scripts": { "deploy": "netlify deploy --dir=dist"}
We want to let Nx know that the build
task needs to be run before the deploy
task, so we add a dependsOn
property for that target.
{ "scripts": { "deploy": "netlify deploy --dir=dist" }, "nx": { "targets": { "deploy": { "dependsOn": ["build"] } } }}
If you want to keep the script next to its Nx configuration, you can rewrite the above configuration like this:
{ "scripts": {}, "nx": { "targets": { "deploy": { "command": "netlify deploy --dir=dist", "dependsOn": ["build"] } } }}
Replace the deploy
script with whatever terminal command you use to deploy your site.
The "dependsOn": ["build"]
setting tells Nx to make sure that the project’s build
task has been run successfully before the deploy
task.
With the deploy
tasks defined, you can deploy a single application with nx deploy react-store
or deploy any applications affected by the current changes with:
nx affected -t deploy
- Stubbing git
- Installing dependencies