Home > Software engineering >  VS Code: How to reference and alter variables from separate javascript file
VS Code: How to reference and alter variables from separate javascript file

Time:03-20

I have two separate javascript files due to me needing to run one as type="module" in my html (since I'm importing a math library from https://mathjs.org/index.html), and needing to run one as type="text/javascript" (as the function inside it wouldn't run inside a module for some reason).

Here is the first js file, app.js:

var turn = "X"

function play(cell) {
    cell.value = turn;
    grid[1][2] = X;
    console.log(grid[1][2])
    if(turn == "X")
    {
        turn = "O"
    }
    else 
    {
        turn = "X"
    }
    cell.disabled = true;
}

Here is the other js file, mathimport.js:

import 'math.js'
import 'mathjs'

var grid = [[0,0,0],[0,0,0],[0,0,0]]
export {grid}

Here is the important part of my html:

<head>
    <link rel="stylesheet" href="style.css">
    <script type="text/javascript" src="app.js" defer></script>
    <script type="module" src="mathimport.js" defer></script>
</head> 

As you can see, I'm trying to access grid from mathimport.js inside app.js, but I keep getting this error:

Uncaught ReferenceError ReferenceError: grid is not defined
    at play (c:\Users\C2Ran\Practice\Game\app.js:5:5)
    at onclick (c:\Users\C2Ran\Practice\Game\index.html:16:82)

Shouldn't grid be globally defined? Why isn't app.js able to access it? And finally, why can't I define my function inside a module in the first place?

CodePudding user response:

You need to import grid in app.js file

Like this:- ìmport {grid} from 'mathimport.js'

CodePudding user response:

If you want to use the exports from a module, then that module can't be the entry point for the program. Exports are not turned into globals.

The code that needs to use it must import it, which requires that it be a module.

  1. Remove <script type="module" src="mathimport.js" defer></script>.
  2. Make <script type="text/javascript" src="app.js" defer></script> a module
  3. import mathimport.js inside app.js

You'll then need to do something with play to use it. Currently app.js only defines it. It never calls it / assigns it as an event handler / etc.

  • Related