Home > Mobile >  imported variable is somehow being accessed before initialization
imported variable is somehow being accessed before initialization

Time:01-18

This is how my code looks

index.html:

<canvas></canvas>

main.js:

    import Class from "./module.js"
    export const canvas = document.querySelector("canvas") 
    const obj = new Class(args)

module.js:

import { canvas } from "./main.js"
const c = canvas.getContext("2d")

export default class Class{
// code
}

This is the error: Uncaught ReferenceError: Cannot access 'canvas' before initialization (in module.js)

What am I doing wrong?

tried with import function and some other stuff but that's not really efficient.

CodePudding user response:

You can move the canvas declaration to another file that the other two modules import.

canvas.js:

export const canvas = document.querySelector("canvas")

Then, main.js and module.js can import it like so:

import { canvas } from "./canvas.js"
  • Related