Django: How to import a javascript inside another javascript file

Viewed 5547

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

3 Answers

It's definitely not right to use Django template tags inside your JS files, since they will not be processed by Django's template loader. I'd suggest either:

(a) Use only relative path imports in your JS files.

or

(b) Set up your Django STATICFILE_DIRS setting to include the node_modules directory and setting STATIC_ROOT to something like '/static'. Then do your module imports as import { x } from '/static/path/to/module'.

EDIT: Grammar

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"),
]

Mabe you can use a global variable at top of your js importations, because static it's only for django template, you can do something like this inside your template file:

<script>
    var static_path = '{% static "@polymer/polymer/" %}';
</script>

end then import your js files using this path

import { PolymerElement, html } from `${static_path}/polymer-element.js" %}`;
Related