Wednesday, 12 April 2017

Javsascript split main.js into two files (import? require?)

My super-long file (main.js) works fine as is. But I want to split out the functions dealing with 'y' into a separate file for organization. In PHP I would use require('yfunctions.php') and be done with it.

Is there an equivalent in javascript that doesn't require rewriting the function calls?

main.js:

// do stuff

function first(x){
  // do stuff with x
}

function second(y){
  // do stuff to y
  // return y
}

function third(y){
  // do stuff with y
}

ultimately becomes:

main.js:

require('yfunctions.js');
// do stuff

function first(x){
  // do stuff with x
}

yfunctions.js:

function second(y){
  // do stuff to y
  // return y
}

function third(y){
  // do stuff with y
}

The above does not work (it seems). Do I have to add an "exports" declaration to each function in yfunctions.js? Is there not a way to say "export every function in this file as a function?"

(Note, I'm working with node.js / electron ... but I'm curious for general knowledge about how javascript works.)



via Trees4theForest

No comments:

Post a Comment