简体   繁体   中英

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/JIC . It's job is to compress user uploaded on the client-side before uploading them to the server. Eg 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM