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?
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?
Share Improve this question asked May 13, 2019 at 23:14 rtg604rtg604 111 silver badge4 bronze badges 6- 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 Commented May 13, 2019 at 23:19
- OP asked without HTML, as he is writing for discord.js, which requires no HTML code – Snel23 Commented May 13, 2019 at 23:21
-
As you've tagged this
node.js
, the mention ofHTML
is confusing - since node.js is not a browser, therefore there is no HTML – Jaromanda X Commented May 13, 2019 at 23:21 - nodejs supports modules – user5734311 Commented May 13, 2019 at 23:22
- 4 Possible duplicate of How do I include a JavaScript file in another JavaScript file? – Snel23 Commented May 13, 2019 at 23:23
1 Answer
Reset to default 4You 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();