How can I include a file, which contains classes definitions in my server.js file?
I don’t want to use module.exports because I want to use this file in my client javascript code too.
Thank you!
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If you want the module’s contents to be available outside the scope of the file you have to use
module.exports. Making the file also work in a browser just requires you to do some extraif/elsesFor instance:
Now if you’re in Node.js you can reach the function like this:
Or if you’re in a browser you can just call it directly since it’s global:
Otherwise I can recommend Stitch.js which allows you to develop JavaScript code using the CommonJS style
requireand modules, then compile it to also run in the browser with no code changes.Require.js also allows for this type of functionality.
Here’s another SO question about using the same code in node and browsers:
how to a use client js code in nodejs