Ask coding questions

← Back to all posts
Importing variables in Javascript
Aidan72 (11)

ok so say I have two files, "main1.js" and "main2.js", I have a variable in main1.js that I want to be in sync with main2.js, (let's say the variable is "num") would I do:

import var num from 'main1.js'

in main2.js or is this wrong?

eankeen (2051)

From the repl you linked, it won't work because you did not designate your scripts to use ES Modules :).

Like this:

<script src="main2.js" type="module"></script>

When you're importing using ES Modules, you don't add scripts tags for them in your HTML because your're asking the server for the file with this line (in your main2.js)

import { num } from './main1.js';

It's worth noting that when you write the filename, you have to prefix the file the name with some absolute or relative path "/main.js", "./main.js", or to some url: ""

I actually created a repl that shows a working example. :)

If you want more info, I would recommend reading this article. MDN has some wonderful docs for imports and exports.

I read your post again, and if you want a much simpler solution, you can just designate num as a global variable and use that, like in this repl.

Vandesm14 (2645)

Remove the "var" from the statement and it should work.

Aidan72 (11)


SyntaxError: Unexpected identifier

didnt work :/

Vandesm14 (2645)

@Aidan72 can you send a link to your repl?