So I have File1.js that has the main functions for my program. I also have File2.js that has extra functions that I didn't want to include in File1.js because I feel it would be easier to edit the functions in a separate file. Is it possible to call a function in File1.js and have the function defined in File2.js? If so, how can I link the two files together?
Asked
Active
Viewed 5,804 times
-2
-
You could look into using a build tool to concatenate the files together. Otherwise, if you have both file1.js and file2.js linked to in a HTML document, all methods in file1.js should be available within file2.js. – Pytth May 13 '19 at 23:19
-
OP asked without HTML, as he is writing for discord.js, which requires no HTML code – Snel23 May 13 '19 at 23:21
-
As you've tagged this `node.js`, the mention of `HTML` is confusing - since node.js is not a browser, therefore there is no HTML – Jaromanda X May 13 '19 at 23:21
-
nodejs supports [modules](https://nodejs.org/api/modules.html#modules_modules) – May 13 '19 at 23:22
-
4Possible duplicate of [How do I include a JavaScript file in another JavaScript file?](https://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) – Snel23 May 13 '19 at 23:23
-
Question has been answered! Thank you. Sorry for any confusion. – rtg604 May 13 '19 at 23:33
1 Answers
4
You can do so by declaring exports like so:
/* utils.js */
module.exports = {
doSomething: function() {
// code
},
anotherOne: function() {
// code
}
};
/* index.js */
const utils = require('./utils.js');
utils.doSomething();

slothiful
- 5,548
- 3
- 12
- 36