Bundling a Phaser project with Parcel

As opposed to most contemporary web-oriented JavaScript ecosystems, the game development framework Phaser does not come with a bundling solution out of the box, which would allow the use of cutting-edge syntax, or writing code across multiple source files but still referencing only one in the HTML page hosting the project. Fortunately, adding one in the mix is fairly easy and works just as well as one would expect.

There is, however, one tiny caveat; loading an asset (e.g. an image) implies providing its relative path as a string, delegating the underlying logic to Phaser itself:

import Phaser from "phaser";

export default new Phaser.Class({
// ...

preload() {
this.load.image("tiles", "../../assets/map/spritesheet.png");
}
});

In the context of a built project, the above just might fail, since our PNG file will be out of reach from its scope. In the case of Parcel, the way to go is pretty straightforward, and consists of bundling these assets with the code and using its internal mechanism to get a proper reference to their actual location:

import Phaser from "phaser";
import tiles from "../../assets/map/spritesheet.png";

export default new Phaser.Class({
// ...

preload() {
this.load.image("tiles", tiles);
}
});

A similar solution is probably available with other bundlers. Finally, one might argue they would probably be better off loading those assets statically, but that seems to be a somewhat controversial topic with Parcel.