3

I am switching a codebase from 100% browser side, to a mixture of browser side and server side.

The issue i have found is that to get my code to run using node.js i must use modules. In order to make my code into modules, it would require a huge refactor of almost all of my code. The reason is that on the browser many functions were used across files without worrying about any namespacing.

But currently, in node.js i have found no way to achieve this same affect, and all solutions i have found have not worked.

For an example of what i would like, i would like to be able to do this:

////////////
// file1.js
////////////

function someFunction(someArgs) {
    /* run some stuff, calculate some stuff */

    return something;
}

////////////
// file2.js
////////////

function someFunction2(someArgs) {
    /* run some code */

    let someValue = someFunction(someArgs);

    /* run some more code */
}

////////////
// file3.js
////////////

someFunction2(myArguments);


I have tried following solutions found here, but they have not helped me.


"masylum"'s answer does not do what i need.


"Udo G"'s answer, referring to using eval to include the other file in the running file throws this error:

console.log(isWhitelisted("test"));
            ^

ReferenceError: isWhitelisted is not defined
    at Object.<anonymous> (/Users/< snip >/server.js:45:13)
    at Module._compile (module.js:413:34)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:139:18)
    at node.js:999:3

This although was pointed out by Udo G as i am using strict mode:

Please also note this won't work with "use strict";


"Nick Panov"'s answer also did not work for me, throwing the same error as Udo G's answer. This might also be because of the use strict.


Is there any way i can achieve this without refactoring the whole codebase to adhere to using modules?

Community
  • 1
  • 1
Sothatsit
  • 33
  • 2
  • Well all of those answers **should** do the work. And you said it doesn't, but you don't show **any** kind of code.. What do you expect? :) – Andrey Popov Jan 28 '16 at 14:11

1 Answers1

0

Try to use a building step to achieve this. Simple concat of the files will help you. For example, look at https://github.com/contra/gulp-concat

Here is docs related to gulp - https://github.com/gulpjs/gulp/blob/master/docs/getting-started.md

zag2art
  • 3,899
  • 26
  • 35