Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

308
Views
VS Code: How to reference and alter variables from separate javascript file

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You need to import grid in app.js file

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!