commands
So in a tutorial I watched, a guy was putting his commands in index.js, if I move the commands to another file, will it still work?
The command:
5 Replies
• What's your exact discord.js
npm list discord.js
and node node -v
version?
• Post the full error stack trace, not just the top part!
• Show your code!
• Explain what exactly your issue is.
• Not a discord.js issue? Check out #useful-servers.So CommonJS works like this:
You have your main folder (index.js), this is the folder you run.
Any code you put here is executed without hassle.
Now, if I wanted to call a function in another file, say the function is called
sendHelloWorld
, simply putting sendHelloWorld();
in the index.js folder won't work.
Instead, you must go to your sendHelloWorld.js file and write the following code:
module.exports = { sendHelloWorld }
What this does is it essientially exports your function saying "hey other files, you can use this function".
Now, the way to import this function is to do this:
const { sendHelloWorld } = require('./sendHelloWorld.js');
Final code for index.js file:
Final code for sendHelloWorld.js:
Index.js:
module.exports = { sendPong }
sendPong.js:
@oscartwo is this good then?
No
the require bit is importing the code from another file
the exports bit is exporting a thing to a file
this thing must be an object, it could be an array, an object, a function, etc
so if I wanted to export a function to a file, I'd first have to make the function in a file and then export it it
then in my main file I'd import it
if that makes sense
anyway, this is more of a server for Discord JS help than a general JS help server
Yeah
Thank you for your help