0

I am using nodejs server. I have a file with a class in which the functionality is written. The functionality of this class is the same for the backend and for the frontend. I do not want to create two files with the same functionality.

A file with a class has dependencies - other classes in other files.

How to connect files on the backend and frontend? What should the classes look like for this?

nodejs back-end app.js:


let player = new Player();

player.goTo(10,20);

front-end index.js:


let player = new Player();

player.goTo(10,20);

It's files need include to frontend and backend:

Player.js:

Class Player
{
  goTo(x,y){
   Path.pathFinding()
  }
}

Path.js:

Class Path
{
  pathFinding(){
   //doing something
  }
}
Nikita Shahov
  • 281
  • 2
  • 11
  • Simply `import`/`require` it from the right path. May be keep a shared folder between the `server` and `client` directories and import it. That should do. – Panther May 22 '20 at 03:44

1 Answers1

1

You are going to want to put this .js file in the folder from where you are hosting static files to serve to the frontend. Whether this be /public or /views or whatever name you called this folder. And in the file next to your class you type in the keyword export: export class {...}. I'm sure you have already done this but no assumptions. Then in your server file simply import it into your server file like this:

import myClass from "/public/js/myjsfile.js";

Example:

public/js/dog.js:

export class dog {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

server.js:

import dog from "/public/js/dog.js";

The dependencies that are used in dog.js or the client side file will come along with it when you import the file on the backend.

ca1c
  • 1,111
  • 10
  • 23