简体   繁体   中英

How can I use NPM modules with Django inside an app?

I have a Django project with 2 apps. I want to use the Notion API in one of the apps, so I have to install it's NPM module. However, I have never use NPM nor a bundler (I understand I have to use one for the import statement). I have no idea on how to do it. Where should I install the module? Should I install Webpack or something similar? How can I integrate both of this technologies with Django?
Can someone please explain this to me, or reffer to an article/video explaining?
I have been trying for hours now and I can't find anything detailed.
I have checked the following links:

And a lot more.

They either don't have what I need (they are for react), or I can just not understand them. I know there are probably a lot of articles on this, but either I just can't find them, or they are too complicated for me (sorry I'm dumb).

If anyone can help me, it would make my day.

Thanks!

PS I am using Typescript, but I can use vanilla JS if necessary.

You have two things to do in order to get your app working the way you want.

  1. Install, configure, and run a module bundler
  2. Use collectstatic

Module bundler:

You have a few choices, but most use webpack because it is the most popular. I prefer rollup but it is all up to preference.

rollup quickstart: https://rollupjs.org/guide/en/#quick-start

webpack: https://webpack.js.org/concepts/

Since you are using Typescript, see the plugins for bundling Typescript

https://webpack.js.org/guides/typescript/

https://github.com/rollup/rollup-plugin-typescript

After you bundle, you should have a main.js file or equivalent. Make sure that main.js is in its own folder. Bundlers will typically do this for you.

Add that directory to your STATICFILES_DIRS in settings.py .

Note that you will need to set a STATIC_ROOT for this to work. This will be a folder that you will store your collected static files at.

Run python manage.py collectstatic

Sidenote: if you are using python manage.py runserver to start your application, you don't need to run collectstatic

For those looking for a -workaround solution- this should be great

I found this website that provides you with the bundles to imported in your static files (.html)

So, for my case I needed to download Chart.js latest version's bundle and I found it available here

https://cdnjs.com/libraries/Chart.js

and add it to your html like so:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js" integrity="sha512-sW/w8s4RWTdFFSduOTGtk4isV1+190E/GghVffMA9XczdJ2MDzSzLEubKAs5h0wzgSJOQTRYyaz73L3d6RtJSg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

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