Now our dependency graph looks a bit disconnected. The frontend and the API still do not have anything in common. The power of Nx libraries is that they can be shared among any number of projects.
We'll look at creating libs to store Typescript interfaces and then we'll use the Nx Move generator to move that library around our project, with minimal effort.
- Explore other real-world examples of creating shared libs for a specific project
- Learn to use the
move
generator
App Screenshot
No change in how the app looks!-
Stop serving both the API and the frontend
-
Generate a new
@nx/js
lib calledutil-interface
inside thelibs/api
folder.⚠️ It's important that we create it in the/api
folder for now -
Create your
Game
interface: seelibs/api/util-interface/src/lib/
api-util-interface.ts -
Import it in the API service:
apps/api/src/app/games.repository.ts
⚠️ You might need to restart the Typescript compiler in your editor🐳 Hint
import { Game } from '@bg-hoard/api-util-interface'; const games: Game[] = [...];
-
Build the API and make sure there are no errors
🐳 Hint
nx build api
-
Inspect the dependency graph
-
Make sure to commit everything before proceeding!
Our frontend store keeps a list of Game
s in state:
const [state, setState] = useState<{
data: any[];
loadingState: 'success' | 'error' | 'loading';
}>({
data: [],
loadingState: 'success',
});
But it's currently typed to any
- so our component has no idea about the shape of the objects it uses!
Let's fix that - we already have a Game
interface in a lib. But it's nested in the api
folder - we need to move it out to the root libs/
folder so any project can use it!
-
Use the
@nx/workspace:move
generator to move the interface lib created above into the root/libs
folder⚠️ Make sure you use the--dry-run
flag until you're confident your command is correct🐳 Hint 2
Use the
--help
command to figure out how to target a specific project Alternatively, check out the docs🐳 Hint 3
Your library name is
api-util-interface
- to move it to root, its new name needs to beutil-interface
-
We can now import it in the frontend components and use it when making the
http
request:🐳 Hint
Frontend store shell app:
apps/store/src/app/app.tsx
import { Game } from '@bg-hoard/api-util-interface'; const [state, setState] = useState<{ data: Game[]; loadingState: 'success' | 'error' | 'loading'; }>({ data: [], loadingState: 'success', });
Routed game detail component:
libs/store/feature-game-detail/src/lib/game-detail/game-detail.tsx
const [state, setState] = useState<{ data: Partial<Game>; loadingState: 'success' | 'error' | 'loading'; }>({ data: {}, loadingState: 'success', });
⚠️ Notice how we didn't have to update the imports in the API. Themove
generator took care of that for us!
-
Trigger a build of both the store and the API projects and make sure it passes
-
Inspect the dependency graph
-
Inspect what changed from the last time you committed, then commit your changes
🎓 If you get stuck, check out the solution