0

I have static files in django call it A.js and B.js

in A.js I have for example for constant like

const variable = "Hello, World"
export {variable}

in B.js I have:

import {variable} from './A.js'

Kindly note that both files are in the static files directory of django project.

My question is how am I going to import successfully the variable so that it checks into variable and use them in the template without getting exceptions

Uncaught SyntaxError: Unexpected token 'export' and the whole JS does not work

I also needed to declare them as modules inside the template

 <script src='{% static "js/A.js" %}' type="module" ></script>
 <script src='{% static "js/B.js" %}' type="module" ></script>

either ways not working. I have previously used export default approach , still not working

Ivan Starostin
  • 8,798
  • 5
  • 21
  • 39
optimus
  • 140
  • 8

2 Answers2

0

Try doing

export default variable

instead of

export {variable}
  • tried that not working – optimus Jul 01 '23 at 20:37
  • Check this out, it might help https://stackoverflow.com/questions/30313314/django-how-to-include-javascript-in-template – Usman Ali Syed Jul 01 '23 at 21:18
  • thats not the correct answer, this is about making javascript .js files communicate with each other not just loading static files into the template, import and exports statement cause issues and reference error, that is what the question about – optimus Jul 01 '23 at 21:31
  • https://stackoverflow.com/questions/56411810/how-can-i-access-a-variable-from-another-file-in-javascript – Usman Ali Syed Jul 01 '23 at 21:42
  • Sorry mate, but django static files is not just like normal javascript and html – optimus Jul 02 '23 at 13:17
0

Okay guys I found that django does not require webpacks import or export statement in order to access javascript variables, Remember the `**

python manage.py collectstatic

**` , it does the job of managing or you can also say bundling your django static files into a single file

In ruby on rails , there is an application.js or application.css, which is a root of all the other javascripts or css file within the assets folder of the rails framework

In a similar way, django does not specify a single file but its designed to automatically make all the files in a static folder visible to each other

thus without any import statement or export statement I can easily call the variable in B.js which is defined in A.js

optimus
  • 140
  • 8