1

I'm making a Discord Bot and I have all of the code in one file. I want to separate all this into multiple files. For example, I could have

  • index.js which has all my requires (var fs = require('fs') etc).
  • message.js which holds all message events. etc etc.
  • How would I reference each file in the index.js file?
Community
  • 1
  • 1
  • 1
    Possible duplicate of [How do I include a JavaScript file in another JavaScript file?](http://stackoverflow.com/questions/950087/how-do-i-include-a-javascript-file-in-another-javascript-file) – bra_racing Mar 30 '17 at 16:03
  • Not quite, since the answer there refer's to including JS on Front-End clients (browser). Whereas here it seems to be a backend import. Correct me if I'm wrong @Rusty – AP. Mar 30 '17 at 16:07
  • @AP. Right that question was only about the JavaScript tag, but it says JavaScript in general so it wasn't really accurate because it did not include anything about Node or details on new standards that people use with webpack etc. I updated that answer to include the Node.js tag and an example for Node and ES6 modules. – Jason Livesay Mar 30 '17 at 16:40

2 Answers2

0

Well, you wouldn't. What you would do instead is leverage require's to the child files, or es6 harmony Import/Exports. Like so:


Using module.export syntax:

index.js

const fs = require('fs')
/*...Other Imports...*/

// Get access to messages data
const callbacks = require('./messages')

messages.js

const fs = require('fs')
/* Setup Callbacks */
module.exports = callbacks

The Harmony Way:

index.js

import fs from 'fs'
/*...Other Imports...*/

// Get access to messages data
import {callbacks, variable1, closure2} from './messages'

messages.js

import fs from 'fs'
/* Setup Callbacks */
export {callbacks, personalClosure as closure2, variable1}

Note: You will require babel to run this code (harmony import/export) since it's not fully suported yet [As of 3/2017]

Community
  • 1
  • 1
AP.
  • 8,082
  • 2
  • 24
  • 33
  • Would I put `module.exports = callbacks` at the bottom of my code? And for extra files could I just make up a new name instead of callbacks? –  Mar 30 '17 at 16:10
  • Yes, exactly... That's the standard way of doing it – AP. Mar 30 '17 at 16:13
0
//message.js
module.exports={
  'somedata':'here are the message',
 ...
}
//index.js
var message = require('index.js');
console.log(message.somedata);//shows here are the message
Vinayk93
  • 353
  • 1
  • 6