0

I have 3 arrays whose elements are defined in a function. And later on, there is another file that needs to be able to read these. But I don't know how to allow the second file to see it.

Start.js

var array1 = [];
var array2 = [];
var array3 = [];

function doThings() {...} // The function will add things to the arrays  

main.js

// Do things with the arrays

I've tried using require() but I get Uncaught ReferenceError: require is not defined

I've also tried using import() but I get Uncaught SyntaxError: Cannot use import statement outside a module

And when I try to add type='module' to make <script type='module 'src="main.js" ></script> I get: from origin 'null' has been blocked by CORS policy


Can someone tell me what I'm doing wrong and how to fix it? Thanks in advance!

Alex
  • 17
  • 5

2 Answers2

0

require and import are set up through bundlers, so if you are just loading js through script tags in your html file, add each js file to your html as scripts in the properly descendent order. so load start.js first, then main. then, if you are declaring your arrays outside a class, main should have access to them.

<script src="./start.js"></script>
<script src="./main.js"></script>

i would add them in the head, and make sure the "./" is followed by whatever the actual file path is to your js files.

ahrampy
  • 50
  • 1
  • 7
  • When I do this the other file (main.js in this case) says that the variables are undefined. (I have console.log(array) in the main.js file, and it prints undefined on the console) – Alex Mar 30 '20 at 00:10
  • check your names, this approach should work as long as your variables are declared outside any class / object / function. same question was answered here, specifying the use of global scope: https://stackoverflow.com/questions/3244361/can-i-access-variables-from-another-file – ahrampy Mar 30 '20 at 08:41
0

If yoy want to use import, you have to set up Webpack. It will bundle all your code with imports into one huge file and connect it to the html.

You also can't use require (CommonJS modules) without NodeJS (you can't read files on the client side due to security issues).

One way how you can use another js file is connecting file to html as a <script /> tag.

Max Starling
  • 598
  • 3
  • 7
  • What do you mean by "as a tag" (I am using script tags. But idk if does something else) – Alex Mar 30 '20 at 00:05