4

I wish to use date-fns in my django project but not entirely sure how to proceed - I cannot rely on a CDN and need to somehow get it installed. I have run npm init in my root folder followed by npm install date-fns. This generated a node_modules folder and a package.json file.

Not entirely sure how to proceed after this. What are the necessary steps?

Do I just use

<script src="{% static 'node_modules/date-fns' %}"></script>

in my base.html file?

erikvm
  • 858
  • 10
  • 30

1 Answers1

4

The search path used when the static template operator is used is defined in the settings.py file in STATICFILES_DIR (docs). This will allow the static operator to find the library files and generate the URL.

Note, however, that the files still need to be served by the web server from the expected path defined by STATIC_URL. The manage.py tool in the project root includes a command collectstatic that can copy all of the static search directories into one location to make serving those files simpler.

Also note that you showed a code sample that references the npm library directory from the script tag as a script, but that the browser will not know how to find the script from the directory. node usually uses the library's package.json to find the entry point. It will be necessary to specifically call out the script files of interest inside the package.

One option is to use a bundling tool like webpack or rollup to collect all of the resources into a single location.

Another option is to add the node_modules paths to the static path, perhaps with prefixes. It might look something like the following.

STATIC_URL = '/static/'
STATIC_ROOT = 'dist/static/'
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'static'),
    # This defines a prefix so the url paths will become `/static/node_modules/...`
    ('node_modules', os.path.join(BASE_DIR, 'node_modules/')),
)

Specifically include index.js rather than just date-fns from the template file.

{% load static %}
<!-- .... -->
<script src="{% static 'node_modules/date-fns/index.js' %}"></script>

If collecting and serving static files from STATIC_ROOT the following command would collect the STATICFILES_DIRS contents, in this example, into dist/static.

python manage.py collectstatic
user650881
  • 2,214
  • 19
  • 31