Hassan Baig Hassan Baig - 1 month ago 14
Javascript Question

Using JavaScript library installed via npm in Django template

I have rudimentary experience with JavaScript, centered around predominantly using JQuery.

In a Django project I'm building, I typically import my JQuery code into a Django template like so:

<script type="text/javascript" src="{{ STATIC_URL }}js/preloader.js"></script>
.

Now I need to use a JS library that's installed via
npm
. Specifically this one: github.com/brunobar79/J-I-C. It's job is to compress user uploaded on the client-side before uploading them to the server. E.g. I can do
target_img.src = jic.compress(source_img,quality,output_format).src;
.

But how would I call this compress method in my template?

As in, where/how do I import it? Should I dump all the library's code in a separate file and import it via
<script type="text/javascript" src="{{ STATIC_URL }}js/JIC.min.js"></script>
?

If I were to do that, then why install the library via
npm
at all?

Like I said, my knowledge in this domain is rudimentary. Would be great to get an illustrative example that clears my concept.

Answer Source

Node packages libraries, are usually bundled into a public/bundle.js file. For this you need a bundler like browserify / webpack / rollup etc.

You would also need to create separate bundle step with npm in your deployment pipeline, which would bundle all your js files into a bundle.js file.


However, if you don't a heavy js app, you can just put the min.js file somewhere in the static folders manually.