How to import inside JavaScript files and using Django to load another js.
Statements like these don't work:
import { PolymerElement, html } from '{% static "@polymer/polymer/polymer-element.js" %}';
import '{% static "@polymer/app-layout/app-drawer/app-drawer.js" %}';
And also these too:
import { PolymerElement, html } from '@polymer/polymer/polymer-element.js';
import '@polymer/app-layout/app-drawer/app-drawer.js';
// myapp-shell.js
import `${static_path}`;
//....
<!DOCTYPE html>
<html lang="en">
    <head>
        {% load static %}
        <script src="{% static 'node_modules/@webcomponents/webcomponentsjs/custom-elements-es5-adapter.js' %}"></script>
        <script src="{% static 'node_modules/@webcomponents/webcomponentsjs/webcomponents-loader.js' %}"></script>
        <!-- Loading app-shell -->
        <script>
            var static_path = '{% static "my-icons.js" %}';
            console.log(static_path);
        </script>
        <script type="module" src="{% static 'mycomponents/myapp-shell.js' %}"></script>
    </head>
    <body>
        <myapp-shell></myapp-shell>
    </body>
</html>
Is there is a way to do that without bundling the code in one big file, nor calling all files may be needed in the html file. Thank you
I searched that for a long time and the way I found to do that is:
inside your mains script use this function.
function include(file) { 
  
    var script  = document.createElement('script'); 
    script.src  = file; 
    script.type = 'text/javascript'; 
    script.defer = true; 
    
    document.getElementsByTagName('head').item(0).appendChild(script); 
    
} 
then load your script like this:
include('/static/js/your_js_file.js');
don't forget to register your static files directory in settings.py
example:
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, "your_folder of library"),
]
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With