Uncaught SyntaxError: Cannot use import statement outside a module

Here is an example script, where you drag your module .js asset at moduleAsset, and you need to provide a global name to reference your module.

Later in your code, after it has loaded, you can access it like this:

MyModuleName.methodName();

Here is the script:

var ModuleLoader = pc.createScript('moduleLoader');

ModuleLoader.attributes.add('moduleAsset', {
    type: 'asset',
    assetType: 'script'
});

ModuleLoader.attributes.add('className', {
    type: 'string',
    default: 'MyModuleName'
});

// initialize code called once per entity
ModuleLoader.prototype.initialize = function() {
    
    if(!this.moduleAsset) return;

    let path = this.moduleAsset.getFileUrl();

    // --- check if it's an absolute path, if not update
    if (path.indexOf('http') !== 0 && window.location.origin.indexOf('launch.playcanvas.com') === -1) {
      path = window.location.origin + window.location.pathname + path;
    }    

    import(path).then( (module) =>{
        window[this.className] = module[this.className];
    });
};
1 Like