Skip to content
Advertisement

How to make Node and React app to share classes

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.

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement