最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

node.js - How to link two JavaScript files together? NO HTML - Stack Overflow

programmeradmin1浏览0评论

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 of HTML 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
 |  Show 1 more ment

1 Answer 1

Reset to default 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();
发布评论

评论列表(0)

  1. 暂无评论