0

I am defining pageId = 3 in JavaScript in one file and socket = io() in another file and I want to use these variables in other files.

I guess I should use modules in ES6, but I am not sure how to do this.

Right now it does work since I am defining the two variables in files that are loaded before the files where I actually use the variables, but it seems like bad code, and my code IDE editor gives me a warning that the variables aren't defined, because it cannot see it in the current file.

I have read a few tutorials, but I still can't see how to define a variable in one file and export it to other files.

Would it just be

const pageId = 3;
const socket = io(); // which is defined in file 'socket.io-1.4.5.js' which is loaded before this file

module.exports = { pageId, socket };

and then import it in the other files with

const pageId = require('pageId');
const socket = require('socket');

socket.on('connect', ...);
(...)

without even loading these files anywhere?

mortensen
  • 1,167
  • 2
  • 13
  • 23

1 Answers1

0

Well, i know it sounds silly ( specially pageId example ), bud there are scenarios that even that is required

Imagine you're building a Physics/mathematics library with some hundred of modules. It Makes Sense. to declare mathematical constants in only one place And load them only when they're needed

Probably exporting them one by one it's not the best solution, but IS a solution that works

As for the io object. It also makes sense to me to declare it, change some configuration values and then, re-export it, with the new configuration, everywhere it's needed instead of creating a new one and reconfigure it everywhere ( supposing that this behaviour works, something that I doubt)

Anyway, the syntax of your sample is incorrect... You cannot "require" and individual var or function that way. Suposing your firstfile is called "strange.js", it should be done like :

const pageId = require('strange').pageId
const socket = require('strange').socket;
mtsdev
  • 613
  • 5
  • 11