Skip to content

3.5 ‐ 05 Importing modules

WhyTry313 edited this page Sep 21, 2023 · 11 revisions

Description

The static import declaration is used to import read-only live bindings which are exported by another module.

Before you go further, no, require is not supported, the ECMAScript repo might mention it but that's an error, only import is supported to this date.

Syntax

In GDScript, var varname = load("file.jsx") is equivalent to import varname from "file.jsx".

import Any:variable from string:filepath(js/jsx);
// or with destructuring
import { str:propery, ... } from string:filepath(js/jsx);

How to use it with examples

As said previously, import and godot.load have both the same function however import requires to be at the beginning of the script, which means it includes initial scripts and can be run further in the script, whereas godot.load can be called at runtime.

In this example you can see how to:

  • load a script on ready and at runtime
  • load a scene and instanciate it
  • attach the script to the scene
  • pass values
  • add as child
import myInitialValues from "./values.json";

export default MyClass extends godot.Node {
    _ready() {
        const myLoadedScript = godot.load("./scripttRuntime.jsx");
        const myObject = godot.load("./myObjectScene.tscn");
        const myObjectInstance = myObject.duplicate();

        myObjectInstance.set_script(myLoadedScript);
        myObjectInstance.myLoadedScriptMethod(myInitialValues);

        this.add_child(myObjectInstance);
    }
}

Do's and dont's

What can you expect from import:

  • import a .js file
  • import a .jsx file
  • import a .json file
  • import npm ES5/ES6 modules - see dont's for npm NodeJS modules
    by building them first as shown in the 🔗 npm_module example

What can't you expect:

  • Use require
    Not implemented
  • Import NodeJS modules
    NodeJS is not included
  • Import NodeJS npm modules
    even if built with npm_modules example, NodeJS is still not included
  • Import a browser based library
    Import and functionalities might work but there's no browser so no DOM or window