Node Nx Tutorial - Step 3: Share Code

Awesome! The application is working as expected!

Next, work on refactoring a bit. The next work to do is move the Todo type to it's own library. This is important when you want to share the type between multiple applications, without having to duplicate the same type everywhere.

Run the following generator to create a library:

nx g @nrwl/workspace:lib data

The result should look like this:

myorg/
├── apps/
│   └── todos/
├── libs/
│   └── data/
│       ├── src/
│       │   ├── lib/
│       │   │   └── data.ts
│       │   └── index.ts
│       ├── jest.config.js
│       ├── tsconfig.lib.json
│       ├── tsconfig.json
│       └── tsconfig.spec.json
├── tools/
├── nx.json
├── package.json
└── tsconfig.base.json

Copy the type into libs/data/src/lib/data.ts.

1export type Todo = {
2  message: string;
3  done: boolean;
4};
5

A note about VS Code :

If you're using VS Code it may be necessary at this point to restart the TS server so that the new @myorg/data package is recognised. This needs to be done every time a new workspace library is added.

Use the command palette with a *.ts file open and choose Restart TS Server.

Refactor the todos service

Now update apps/todos/src/app/todos/todos.service.ts to import the type:

1import { Injectable } from '@nestjs/common';
2import { Todo } from '@myorg/data';
3
4const todos: Todo[] = [
5  { message: 'Take out trash', done: false },
6  { message: 'Continue using Nx', done: false },
7];
8
9@Injectable()
10export class TodosService {
11  getTodos(): Todo[] {
12    return todos;
13  }
14}
15

Every time you add a new library, you have to restart nx serve. So restart nx serve todos and you should see the application running.

What's Next