0

I want to include a javascript file into a main file. Unlike C/C++, where #include means "include all variables and functions", export/import and module.exports are only suitable for moduled files. How can I implement the one of C/C++ in javascript without using eval()? Here's an example.

header.js

var a = 1;
function b(){};

main.js

// How can I include header.js?
console.log(a);
console.log(b());
Phil Ross
  • 25,590
  • 9
  • 67
  • 77
Riddle Aaron
  • 73
  • 1
  • 2
  • 8
  • What do you mean by "moduled file"? What is wrong with using modules? – Bergi Jan 30 '18 at 11:34
  • 1
    What environment are you in? Clientside js in browsers, serverside node.js, something else? – Bergi Jan 30 '18 at 11:35
  • In C/C++ `#include` basically means "paste the whole file contents (mostly function declarations) here", and you have modularisation by scopes per compilation unit. You don't want to that kind of includes in JavaScript. – Bergi Jan 30 '18 at 11:37
  • If this is in a browser, you can easily do it the old fashioned way with `` followed by `` in your HTML. Global variables are shared among all script tags. – Michael Geary Jan 30 '18 at 11:38
  • @RiddleAaron In Node.js, you can use `module.exports = { b };` and `const { b } = require('./header')` – JLRishe Jan 30 '18 at 11:47
  • @Bergi Yes, pasting the whole file is what I want to do. And I'm serverside node.js. Moduled file means a file that uses export clause in ES6 or exports in node.js. I don't know what word means such files. – Riddle Aaron Jan 30 '18 at 11:51
  • @JLRishe How about plural variable and functions? – Riddle Aaron Jan 30 '18 at 11:52
  • @RiddleAaron But if you were to include `header.js` in multiple files, you would get multiple instances of your variables/functions?! Or even worse, you'd get name collisions between them. Why not use ordinary imports/exports? – Bergi Jan 30 '18 at 11:55
  • @RiddleAaron Yes, you can use the same technique for as many variables and functions as you want. – JLRishe Jan 30 '18 at 12:19

0 Answers0