Import class other file syntax error

I must admit I don’t fully understand how to use modules from the Processing IDE but I managed to get this to work

AnimalDemo.js

import Animal from "./animal.js";

function setup() {
    createCanvas(200, 200);
    const dog = new Animal("dog");
    // console.log(dog)
    dog.sayName();
}

function draw() {
    background(220);
}

window.setup = setup;
window.draw = draw;

animal.js

class Animal {
    constructor(name) {
        this.name = name;
    }
    //Print Animal
    sayName() {
        console.log(this.name);
    }
}

export default Animal;

Both these need to be loaded as modules so in the html file change the ‘type’ to ‘module’

  <!-- PLEASE NO CHANGES BELOW THIS LINE (UNTIL I SAY SO) -->
  <script language="javascript" type="text/javascript" src="libraries/p5.min.js"></script>
  <script language="javascript" type="module" src="animal.js"></script>
  <script language="javascript" type="module" src="AnimalDemo.js"></script>
  <!-- OK, YOU CAN MAKE CHANGES BELOW THIS LINE AGAIN -->

This was based on a reply by @GoToLoop in this discussion

2 Likes