I'm just getting into client/server architecture and am not sure if there is a best practice for this. I have a file structure as follows:
.
|-public
| |-index.html
| |-client.js
| |-src
| | |-person.js
|-server.js
person.js is a class that I would like to share between the server and the client. socket.io lets me send over a json object, but I cannot find a way to send methods attached to a Person(). So instead, I'm resorting to sending over a json and reinitializing the Person object. This also leads me to some import issues.
On server.js:
const { Person } = require('./public/src/person')
...
io.on('connection', client => client.emit('init', new Person({data}))
On client.js:
let person;
socket.on('init', handlePerson);
function handlePerson(data) {
person = new Person(data);
person.method();
...
}
While this works, I'm wondering if there's a better way to do it. It's also forcing me to put an ugly export at the bottom of person.js:
if (typeof module !== 'undefined') {
module.exports = {
Overworld
}
}
where the server requires the inner module.exports, but the client would get
Uncaught ReferenceError: module is not defined
I should add, my index.html is importing the js files like so:
<script src="/socket.io/socket.io.js"></script>
<script src="/src/Overworld.js"></script>
<script src="/client.js"></script>
I think one of these files must be seriously cringe for an experienced js developer. Any help or explanation would be appreciated!