'inside a script module, try to import js files with twig asset() (error: myalias.x is not a function)

[ Environment: symfony (PHP), twig files with HTML/JS code, and Managing assets with Webpack ]

Files Tree

_assets
 |__js
    |__file.js
    |__library
       |__ps
          |__index.js
_public
 |__build
    |__js
       |__myfile.js (auto generated by webpack)

_src
_templates
 |__mypage
    |__page.html.twig

_webpack.config.js

Normally in a file.js you perform an import, and then use/call the exported functions/variables using the alias given:

library/ps/index.js

export function x(){
   console.log('hi !');
}

file.js

import * as myalias from "../../../assets/js/library/ps";

myalias.x();

webpack.config.js

...

.addEntry('js/myfile', './assets/js/file.js')

...

page.html.twig

...

{% block javascript %}
   {{ encore_entry_script_tags('js/myfile') }}
{% endblock %}

...

web console (google chrome)

hi !

(EVERYTHING UTIL HERE WORKS PERFECTLY)


Files Tree

_assets
 |__js
    |__library
       |__ps
          |__index.js
_public
 |__build
    |__js
       |__mylibrary.js (auto generated by webpack)

_src
_templates
 |__mypage
    |__page.html.twig
    |__page_JS.html.twig

_webpack.config.js

My Goal is to do the same thing, but having the JS code in a twig file. Because I gain more advantages passing, in some cases, the twig variables to the js code.

The problem is that I get an error, in the web console. Uncaught TypeError: myalias.x is not a function

library/ps/index.js

export function x(){
   console.log('hi !');
}

webpack.config.js

...

.addEntry('js/mylibrary', './assets/js/library/ps/index.js')

...

page_JS.html.twig

<script type="module">

    import * as myalias from "{{ asset('build/js/mylibrary.js') }}";

    myalias.x();

</script>

the code is inside the <scrip type="module">, because with it, we can use the import/export functionalities that normally inside a normal <script> we don't have. (if I understood right) PS. the path is build because the webpack generate the file in the public folder.

page.html.twig

...

{% block javascript %}
   {% include 'mypage/_page_JS.html.twig' %}
{% endblock %}

...

web console (google chrome)

Uncaught TypeError: myalias.x is not a function


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source