Using additional scripts
As noted previously, the only script Construct automatically loads and runs is the main script. This appears in bold in the Project Bar.
When you select script files, the Properties Bar shows a Purpose property for the script. The main script has the purpose set to Main script, and you can only have one main script in your project.
To use any other script files in your project, you must import
them from the main script. This also lets you control the order they are loaded and run. These other script files should have the Purpose set to '(none)' (indicating Construct won't use it automatically) and also export
the things it wants to be used by other scripts. See the Imports & exports example for a basic demonstration of using modules in Construct.
To learn more about imports and exports, refer to the MDN guide on JavaScript Modules.
Integration with scripts in events
Unlike legacy "classic" mode scripts, modules have their own top-level scope. This means things like a top-level function declaration is not available in other script files.
Instead you can add imports to the script file with the purpose Imports for events which then become available for scripts in events. See the section Using imports in Scripts in event sheets for more details.
Another option is to write globals as explicit properties of globalThis
, e.g. globalThis.myFunction = function () { ... }
and call it via globalThis.myFunction()
, but using modules is preferable.
Errors
Unlike scripts in event sheets, errors arising from the top level of script files are not automatically handled by Construct. If an unhandled exception is thrown, the browser will halt any further execution of script in that file. Typically this causes the rest of your code to stop working, and is considered a crash. See the section debugging scripts to find out how to deal with such issues.
Note one difference is exceptions or rejections in a runOnStartup
callback are automatically handled by Construct. The error will be logged to the browser console and the runtime will continue to start up and run the game - but note if an error occurred it may not run as expected.