Home > Back-end >  How can I use NPM modules with Django inside an app?
How can I use NPM modules with Django inside an app?

Time:11-24

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!

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

CodePudding user response:

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

  • Related