How to make Node and React app to share classes

Viewed 257

I'm building a Node and React app, both using TypeScript. Its directories tree is as follows:

enter image description here

My question:

Since I'm using the same language for both stacks, and in the future the React Native will be added also using TypeScript, I wonder how I can create one group of classes to be used for all of them.

Why I want to do this:

DRY (Don't repeat yourself): My intention is to take full advantage of using the same programming language in all layers so there's no sense creating two equal classes.

What I have tried so far:

I created a third folder called "util" and put a generic class just to test both Node and React using it. Like this:

enter image description here

In Node.js I used the command below to import it:

import Person from "../../util/person.class";

And in React.js, I used the same logic to import it:

import Person from "../../util/person.class";

As I already expected, both deny using files that are outside their respective root folders:

enter image description here

enter image description here

I also searched in the internet about this and I found some "eject" command that, once used, there's no way back, whatever. I'd like to avoid such ways. Is there any approach where I could take in my favor?

I also want to mention that I created a tsconfig.json for backend using "tsc --init" and set the rootDir as "./src/" and outputDir as "./dist/".

Thanks.

2 Answers

You could set up a third project that has the shared functionality. Then you can publish the shared package to a npm repository. And then you can install the shared package in the frontend and backend project.

If you want to send the react from the sever then the front-end files should be under the back-end folder

/app root
   / back-end
      /shared-front-end-classes
      /front-end-desktop
      /front-end-mobile

Though this is not the best solution

The best solution is to host the front-end on a different server and make the back-end totally functional with APIs

For example :

I have a blog that I host the

Front-end:

Github pages "Support react via a small npm package"

Back-end:

Hosted on Heroku

DB:

I am using mongoAtlas "A cloud DB"


now you have 3 separate places to hold all of your code independent of each other

Now for your other problem, you want to use the same classes over the two front-ends

For me, I usually make a small repo with all the components/ pages that I want then import this in any project for future use

I am not sure if this follows the DRY concept but you will not write your code twice

Related