ESM Scripts
A modern way to create PlayCanvas projects
ESM Scripts, leveraging the power of ES Modules, provide a significant improvement over Classic Scripts, offering a more expressive, flexible, and modern approach to creating interactive PlayCanvas projects. They introduce a modular structure that enhances code organization and maintainability. By allowing you to import and export code across modules, ESM Scripts lead to cleaner, more readable code. Compared to classic scripts, ESM Scripts support static imports, improving performance through more efficient bundling and dead code-removal.
You can learn more about ES Modules and their features on MDN.
Getting Started
To create an ES Module Script (ESM Script for short), simply create a script with a name that ends with .mjs
such as Rotator.mjs
.
An ESM Scripts must end with the .mjs
suffix.
You'll notice that the newly created ESM Script has a new boilerplate, based on JavaScript class syntax. Although this looks a little different, it provides exactly the same functionality.
ESM boilerplate
import { Script } from 'playcanvas';
export Rotator extends Script {
initialize() {
}
update(dt){
}
}
If you're not familiar with a class based syntax, this might look unfamiliar. You can learn more about JavaScript classes on MDN. Learn more about an anatomy of the ESM Scripts. A single file can contain multiple ESM Scripts, however each one needs to be exported using an export
keyword.
Only ESM Scripts exported using the export
keyword are exposed to the Editor
Script Attributes
Class members can be exposed to the editor using Script Attributes which allow you to declare a public editor interface. You can learn more about script attributes here
Importing Modules
One of the most important features of ES Modules is their ability to import and export code. For example, you can create a global config.mjs
within a /settings
folder and you can import it into your other scripts.
// settings.mjs
export const ROTATION_SPEED = 0.1;
// Rotator.mjs
import { Script } from 'playcanvas';
import { ROTATION_SPEED } from './settings/config.mjs';
export Rotator extends Script {
update(){
this.entity.rotateLocal(0, ROTATION_SPEED, 0);
}
}
Any ES Module within your project can be imported using a relative file path.
Bundling
When you export a project that contains ESM Scripts, the entire project application is bundled together. The aim is deliver an optimized build of your project that gives a better loading experience for your end users.
Bundling itself is a complex topic, and not one strategy fits all needs. However by default the bundling process will eliminate dead code and minify it's output.