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?

5
  • 1
    Possible duplicate of ES6 module export options Commented Oct 6, 2016 at 18:58
  • In fact when your "require" them, you are loading them, in some way Commented Oct 6, 2016 at 19:08
  • What do you mean by "without even loading these files anywhere?"? Commented Oct 6, 2016 at 19:18
  • I meant loading them with <script src="file_with_page_id.js"></script> Commented Oct 6, 2016 at 19:20
  • @mortensen You've tagged this question node.js, there are no script tags anyway? Commented Oct 6, 2016 at 20:32

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.