Share Types between backend and frontend in a monorepo
To avoid creating duplicate Interfaces and Types in your backend and frontend for DTO´s, parameters and you name it; we can share those types with TypeScripts: Path mapping.
Add a custom path in your frontend/client-side tsconfig.json:
{
"compilerOptions": {
"baseUrl": ".",
"paths": { "@backend/*": ["../server/src/types/*"], },
}
}
- The path is going up a directory from your
baseUrl
and then going toserver/src/types
-directory. - We add * as a wildcard to mean that everything in that directory is to be accessible.
- We call our path
@backend
. This will be used as an alias when using ES6-imports.
Types are now available to be imported from the server-side with ES6-imports:
import { ItemDTO } from "@backend/itemDTO.js"
// the relative server-side path: ./src/types/itemDTO.js
30 december 2022