Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django how to use npm modules with static/ templates

I have recently added npm to my project in order to keep better track of my js dependencies. Previously I have just been git cloning to my static/vendor folder.

I've also added gulp , but have only got it doing hello world things right now. It seems simple enough - it can watch files, minify assets, compile Sass. Eventually I will probably switch to Webpack, but gulp is simple and working for now. I don't want to use django-compressor or django-pipeline.


So let's say I run npm install vis to pull in visjs. It gets added to node_modules and a record is added to package.json dependencies.

A) Do I reference vis/dist right where it is in node_mods in my template scripts?

<script src="/node_modules/vis/dist/min-vis.js' %}"></script>

# right now it's <script src="{% static 'vendor/min-vis.js' %}"></script

B) Should gulp be listening for changes to package.json dependencies and replicating vis/dist to static/vendor or static/js when it sees changes there?


I keep seeing people talking about handling STATICFILE_DIRS when they talk about npm and gulp. Right now mine is just set to the following. Will this change?

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
)
like image 558
Kalanos Avatar asked Jul 13 '18 13:07

Kalanos


1 Answers

STATICFILES_DIRS tells Django where to find all the static assets (which will later be "collected" for a deployment, but we can ignore that for the moment). That setting will need to include wherever you have gulp placing the processed assets, or you can have gulp put them into $BASE_DIR/static to avoid changing your setting if you prefer.

From there, you should be using the static templatetag

{% load static %}
<script src="{% static 'your_bundled_asset.min.js' %}"></script>

Note that if your asset is in a nested directory under the STATICFILES_DIRS entry it is under, you may need to prefix that. {% static 'js/asset.min.js' %}.

So Django can use the dev location ($BASE_DIR/static) or the "collected" location when deployed (./manage.py collectstatic --noinput pulls all static files to one location for simplified serving).

like image 79
nerdwaller Avatar answered Sep 22 '22 20:09

nerdwaller