How to put part of a scene class code in a separate file?

Hi!

One of my scene classes is getting umconfortably big and I would like to put the functions I use internally in a separate file. I searched online but couldn’t find a GOOD example of how doing it.

The basic structure I have is:

class MyScene extends Phaser.Scene {

    constructor () {
    }
    
    init(data) {
    }
    
    preload() {
    }
    
    create() {
    }
    
    update() {
    }

    customFunction1 = () => {
    }

    customFunction2 = () => {
    }

}

export default MyScene;

I’d like to know how to put customFunction1, customFunction2, etc in a separate file for organization purposes.

How can I do this?

Thanks!

import { customFunction1, customFunction2 } from './custom.js';

class MyScene extends Phaser.Scene {/*…*/}

Object.assign(MyScene.prototype, { customFunction1, customFunction2 });
1 Like

Hi Samme!

I made my custom.js like this:

customFunction1 = () => {}
customFunction2 = () => {}

As I couldn’t figure where to put the

Object.assign(MyScene.prototype, { customFunction1, customFunction2 });

I then tried a few different places but I always end with this error:

Uncaught SyntaxError: The requested module ‘./custom.js’ does not provide an export named 'customFunction1’

Also I think I cannot just save the functions in a JS file; otherwise I have to export it first, right? Should I put it into a Phaser 3 Scene class or what???

Thanks!

Were you using imports/exports already?

Only In scenes as I mentioned in the OP…

custom.js

const customFunction1 = () => {};
const customFunction2 = () => {};

export { customFunction1, customFunction2 };

MyScene.js

import { customFunction1, customFunction2 } from './custom.js';

class MyScene extends Phaser.Scene {/*…*/}

Object.assign(MyScene.prototype, { customFunction1, customFunction2 });

// …
1 Like

Cool, thank you Samme! I will give it a try! :slightly_smiling_face:

FYI: You could also write it like this, so you don’t have to put all the functions of one file into the export statement at the end.

export const customFunction1 = () => {};
export const customFunction2 = () => {};

The code for MyScene.js does not change.

Best regards
Nick

1 Like

Thanks Nick!