To avoid importing many unused files in the static folder, I copy the items I need with a Gulp script. I use an NPM script to invoke Gulp after installing the packages, so it doesn't affect my daily workflow.
package.json
:
{
"dependencies": {
"bootstrap": "^4.3.1",
"gulp": "^4.0.2",
"jquery": "^3.4.1"
},
"scripts": {
"install": "gulp"
}
}
gulpfile.js
const { series, src, dest } = require('gulp');
// Task 1: copy bootstap's assets to /_vendor/
function bootstrap() {
const files = [
'node_modules/bootstrap/dist/css/bootstrap.min.css',
'node_modules/bootstrap/dist/js/bootstrap.min.js'
]
return src(files).pipe(dest('_vendor'))
}
// Task 2: copy jquery's assets to /_vendor/
function jquery() {
const files = [
'node_modules/jquery/dist/jquery.min.js'
]
return src(files).pipe(dest('_vendor'))
}
exports.default = series(bootstrap, jquery)
my_project/settings.py
:
STATICFILES_DIRS = [
str(BASE_DIR / '_vendor'), # populated by gulp
]
Django template:
{% load staticfiles %}
<link rel="stylesheet" href="{% static 'bootstrap.min.css' %}" />
Bonus
In the Gulpfile, you can concatenate and minify files. As an example, here is my Gulpfile for Blueimp's file upload library:
const uglify = require('gulp-uglify');
const concat = require('gulp-concat');
// Task 3: minify blueimp's assets and save to /_vendor/
function blueimp() {
const files = [
'node_modules/blueimp-file-upload/js/vendor/jquery.ui.widget.js',
'node_modules/blueimp-file-upload/js/jquery.iframe-transport.js',
'node_modules/blueimp-file-upload/js/jquery.fileupload.js'
]
return src(files).pipe(uglify())
.pipe(concat('jquery.fileupload.min.js'))
.pipe(dest('_vendor/'))
}