1

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.

Fexxix
  • 13
  • 5
  • See [How to fix this ES6 module circular dependency?](https://stackoverflow.com/questions/38841469/how-to-fix-this-es6-module-circular-dependency) – Unmitigated Jan 17 '23 at 14:01
  • @Unmitigated that was too lengthy and i dont have the time (sorry) so i included the module in the head tag before the main one and it works. atleast for the canvas variable – Fexxix Jan 17 '23 at 14:12

1 Answers1

1

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"
Unmitigated
  • 76,500
  • 11
  • 62
  • 80