GameSpark/Tutorials Open editor ↗
JavaScript · Lesson 12

Import and export

As a game grows, one giant file gets hard to read. GameSpark lets you split it across files and share code between them with export and import. Add a file with the + in the Files panel.

1. Export from one file

Say you make a file called coin.js with a helper. The export keyword makes it available to other files:

// coin.js
export function drawCoin(x, y) {
  circfill(x, y, 3, 10);        // gold circle
  line(x, y - 2, x, y + 2, 9);  // center line
}

2. Import into another

In main.js, import brings that function in by name, from the file’s path. Then you use it as if it were defined right there:

// main.js
import { drawCoin } from './coin.js';

function draw() {
  cls(1);
  drawCoin(40, 64);
  drawCoin(64, 40);
  drawCoin(88, 64);
}

The { drawCoin } names exactly what you want from the other file, and './coin.js' says which file to get it from.

3. Why split up?

💡

Only what you export is shared, and only what you import comes in — nothing leaks by accident. That’s why splitting a big game into modules keeps it manageable.

What you learned