Separate Files Don't Work?

I was trying to replicate something from the coding train, and I made a file called block.js which looks like this:

class Block {
  constructor(x,w) {
  this.x = x;
  this.y = height - w;
  this.w = w
  }
  show() {
  fill(255,10,10);
  square(this.x,this.y,this.w);
  }
}

The only difference between mine and his was that he had an image, and I just used a normal square. I tried to use it in sketch.js and the part that doesn’t work looks like this:

let block1;
let block2;


function setup() {
  createCanvas(800, 600);
//Block isn't defined apparently
  block1 = new Block(100,20);
  block2 = new Block(200,150);
}

The weird thing is that when I put class Block in sketch.js, it works just fine, But the coding train’s code was fine in its own file. So what went wrong?

1 Like

Just make sure you’ve got an HTML file where “block.js” is run before “sketch.js”:

<script async src=https://cdn.JsDelivr.net/npm/p5></script>
<script defer src=block.js></script>
<script defer src=sketch.js></script>
1 Like