Want to use npm modules in your django project without vendoring them? django-npm serves as a wrapper around the npm command-line program as well as a staticfiles finder.
$ pip install django-npm
- Install npm. If you use a private registry, make sure your
.npmrc
is set up to connect to it - Have a
package.json
at the root of your project, listing your dependencies - Add
npm.finders.NpmFinder
toSTATICFILES_FINDERS
- Configure your
settings.py
$ npm install
with the command line, or with Python:from npm.finders import npm_install; npm_install()
$ ./manage.py collectstatic
will copy all selected node_modules files into yourSTATIC_ROOT
.
-
NPM_ROOT_PATH
: absolute path to the npm "root" directory - this is where npm will look for yourpackage.json
, put yournode_modules
folder and look for a.npmrc
file -
NPM_EXECUTABLE_PATH
: (optional) defaults to wherevernpm
is on your PATH. If you specify this, you can override the path to thenpm
executable. This is also an absolute path. -
NPM_STATIC_FILES_PREFIX
: (optional) Your npm files will end up under this path inside static. I usually use something likeos.path.join('js', 'lib')
(so your files will be in /static/js/lib/react.js for example) but you can leave it blank and they will just end up in the root. -
NPM_FILE_PATTERNS
: (optional) By default, django-npm will expose all files innode_modules
to Django as staticfiles. You may not want all of them to be exposed. You can pick specific files by adding some additional configuration:NPM_FILE_PATTERNS = { 'react': ['react.js'], 'express': ['lib/*.js', 'index.js'] }
Keys are the names of the npm modules, and values are lists containing strings. The strings match against glob patterns.
-
NPM_FINDER_USE_CACHE
: (default True) A boolean that enables cache in the finder. If enabled, the file list will be computed only once, when the server is started.
If you want to run npm install
programmatically, you can do:
from npm.finders import npm_install
npm_install()
- v1.0.0 - Improve speed, separate
npm install
from the finder - v0.1.4 - Fix bug with
NPM_EXECUTABLE_PATH
(thanks @yohanboniface) - v0.1.3 - Actually fix destination bug
- v0.1.2 - Fix bug with destination prefix
- v0.1.1 - manage.py runserver bugfix
- v0.1.0 - Add
NPM_FILE_PATTERNS
setting - v0.0.1 - initial release