Search code examples
aframear.js

A-Frame component doesn't work with ES6 Modules?


I want to call some function (foo) from another javascript file (a.js) when inside my AFRAME component's init function.

in my index.html something like this:

<script type="module">
    import {foo} from "a.js";
    AFRAME.registerComponent('registerevents', {
     init: function () {
         foo();
     }
    }
}

when I did this, the init function doesn't even get called.

Then I tried something like this:

<script type="module" src="a.js"></script>
<script>
    AFRAME.registerComponent('registerevents', {
     init: function () {
         foo();
     }
    }
}

I got a function not defined in this case.

Then I tried in a.js

window.foo = foo;

in my index.html:

<script type="module" src="a.js"></script>
<script>
    AFRAME.registerComponent('registerevents', {
     init: function () {
         window.foo();
     }
    }
}

Then I got a window.foo is not a function error. What should be the correct way to call a function in the init function? Thanks !


Solution

  • Modules and A-Frame work fine. The problem is that the init method is not called until a component is set on an entity. For instance, you can set it on a-scene as follows:

    <script type="module">
        import {foo} from './a.mjs';
        AFRAME.registerComponent('registerevents', {
         init: function () {
             foo();
         }
        }); 
        AFRAME.scenes[0].setAttribute('registerevents','');                         
    </script>
    
    

    Where a.mjs is:

    
    export function foo(){ console.log('Fooing is believing!')}
    
    

    Working example: https://glitch.com/edit/#!/little-coral