How To share Typescript Types between Frontend and Backend In Big Projects

60 views Asked by At

I have a MERN project with the following folder structure.

backend is an express,mongo backend. With the following structure.

frontend is folder of 3 vite react projects. each has the following folder structure

Parent Folder:
- backend
    - src
        - controllers 
        - middlewares
        - models
        - schemas
        - types
        - utils
        - app.ts
        - package.json
    - tsconfig.json
- frontend
    - client  (this is a vite app)
        - src
            - assets
            - components
            - hooks
            - pages
            - screens
            - types
        - index.html
        - package.json
        - tsconfig.json
    - master  ( this is also same as client)
    - manager (this is also same as client)

In this implementation i have created a Types folder in each of the folders.

backend,

frontend/client,

frontend/master,

frontend/manager

So everytime someone pushes a new change in the type of one thing. i have to change it in all the 4 folders so that they are the same.

MY QUESTION IS:

I want to find a way to declare the Types globally in the Parent Folder so that i am able to use them anywhere in backen or the 3 frontends i want.

The types i want to make global is mainly database document schema which are reused a lot everywhere.

Right now how i am managing the types is by manually copying and pasting regularly. This causes a lot of problem if the types are changing frequently.

Is there a way to do this better??

1

There are 1 answers

1
Satvam Thakkar On

You can update the rootDir property in your tsconfig.json to your monorepo's path and import types from a shared schema folder, follow these steps:

{ 
  "compilerOptions": {
    "rootDir": "./path/to/your/monorepo"
  }
}

import { MyType } from '../../shared/schema/types';