Skip to main content

A Django app to load webpack assets.

Project description

Django Manifest Loader

Build Status Build Status contributions welcome

Always have access to the latest webpack assets, with minimal configuration. Wraps Django's built in {% static %} templatetag to allow you to link to assets according to a webpack manifest file. Handles webpack's split chunks.

Turns this

{% load manifest %}
<script src="{% manifest 'main.js' %}" />

Into this

<script src="/static/main.8f7705adfa281590b8dd.js" />

Installation

pip install django-manifest-loader

Django Setup

# settings.py

INSTALLED_APPS = [
    ...
    'manifest_loader',  # add to installed apps
    ...
]

STATICFILES_DIRS = [
    BASE_DIR / 'dist'  # the directory webpack outputs to
]

You must add webpack's output directory to the STATICFILES_DIRS list. The above example assumes that your webpack configuration is setup to output all files into a directory dist/ that is in the BASE_DIR of your project.

BASE_DIR's default value, as set by $ djagno-admin startproject is BASE_DIR = Path(__file__).resolve().parent.parent, in general you shouldn't be modifying it.

Optional settings, default values shown.

# settings.py

MANIFEST_LOADER = {
    'output_dir': None,  # where webpack outputs to, if not set will search in STATICFILES_DIRS for the manifest. 
    'manifest_file': 'manifest.json',  # name of your manifest file
    'cache': False,  # recommended True for production, requires a server restart to pickup new values from the manifest.
    'ignore_missing_assets': False,  # raises an exception if a file is not in the manifest.
    'ignore_missing_match_tag': False,  # raises an exception if the {match} string is not found in the manifest_match tag
}

Webpack configuration

You must install the WebpackManifestPlugin. Optionally, but recommended, is to install the CleanWebpackPlugin.

npm i --save-dev webpack-manifest-plugin clean-webpack-plugin
// webpack.config.js

const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const ManifestPlugin = require('webpack-manifest-plugin');

module.exports = {
  ...
  plugins: [
      new CleanWebpackPlugin(),  // removes outdated assets from the output dir
      new ManifestPlugin(),  // generates the required manifest.json file
  ],
  ...
};

Usage

Django Manifest Loader comes with two template tags that house all logic. The manifest tag takes a single string input, such as 'main.js', looks it up against the webpack manifest, and then outputs the url to that compiled file. It works just like Django's built it static tag, except it's finding the correct filename.

The manifest_match tag takes two arguments, a sting to pattern match filenames against, and a string to embed matched file urls into. See the manifest_match section for more information.

Single file use (for cache busting) (manifest tag)

{% load manifest %}

<script src="{% manifest 'main.js' %}"></script>

turns into

<script src="/static/main.8f7705adfa281590b8dd.js"></script>

Where the argument to the tag will be the original filename of a file processed by webpack. If in doubt, check your manifest.json file generated by webpack to see what files are available.

The reason this is worth while is because of the content hash after the original filename, which will invalidate the browser cache every time the file is updated. This ensures that your users always have the latest assets.

Split chunks (manifest_match tag)

{% load manifest %}

<script src="{% manifest_match '*.js' '<script src="{match}"/>' %}"></script>

turns into

<script src="/static/vendors~main.3ad032adfa281590f2a21.js"/>
<script src="/static/main.8f7705adfa281590b8dd.js"/>

This tag takes two arguments, a pattern to match against, according to the rules of the python fnmatch package, and a string to input the file urls into. The second argument must contain the string {match}, as it is what is replaced with the urls.

About

At it's heart Django Manifest Loader is an extension to Django's built-in static templatetag. When you use the provided {% manifest %} templatetag, all the manifest loader is doing is taking the input string, looking it up against the manifest file, modifying the value, and then passing along the result to the {% static %} template tag. The {% manifest_match %} tag works similarly, just with a bit of additional logic to find all the necessary files and to render the output.

Suggested Project Structure

BASE_DIR
├── dist
│   ├── main.f82c02a005f7f383003c.js
│   └── manifest.json
├── frontend
│   ├── apps.py
│   ├── src
│   │   └── index.js
│   ├── templates
│   │   └── frontend
│   │       └── index.html
│   └── views.py
├── manage.py
├── package.json
├── project
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── requirements.txt
└── webpack.config.js

Cache Busting and Split Chunks (the problem this package solves)

Tests and Code Coverage

Run unit tests and verify 100% code coverage with:

git clone https://github.com/shonin/django-manifest-loader.git
cd django-manifest-loader
pip install -e .

# run tests
python runtests.py

# check code coverage
pip install coverage
coverage run --source=manifest_loader/templatetags/ runtests.py
coverage report

Contributing

Do it. Please feel free to file an issue or open a pull request. The code of conduct is basic human kindness.

License

Django Manifest Loader is distributed under the 3-clause BSD license. This is an open source license granting broad permissions to modify and redistribute the software.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-manifest-loader-0.0.1.tar.gz (9.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_manifest_loader-0.0.1-py3-none-any.whl (9.7 kB view details)

Uploaded Python 3

File details

Details for the file django-manifest-loader-0.0.1.tar.gz.

File metadata

  • Download URL: django-manifest-loader-0.0.1.tar.gz
  • Upload date:
  • Size: 9.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/50.3.0 requests-toolbelt/0.9.1 tqdm/4.50.0 CPython/3.8.5

File hashes

Hashes for django-manifest-loader-0.0.1.tar.gz
Algorithm Hash digest
SHA256 8f29282b2dde9be6b75a38c0e234ac5b72e0b210d9fb4751a2d8f5428ee0725a
MD5 7daa527a6688519f30e80f5d776f1bd6
BLAKE2b-256 0f45ae5dd07465bcb2f277e877aa34a69fbaf93becbbd934891ebf7c8704eb4c

See more details on using hashes here.

File details

Details for the file django_manifest_loader-0.0.1-py3-none-any.whl.

File metadata

  • Download URL: django_manifest_loader-0.0.1-py3-none-any.whl
  • Upload date:
  • Size: 9.7 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.2.0 pkginfo/1.5.0.1 requests/2.24.0 setuptools/50.3.0 requests-toolbelt/0.9.1 tqdm/4.50.0 CPython/3.8.5

File hashes

Hashes for django_manifest_loader-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 47891956c67574395c7e3652e0f62d21e7008d9c71653c757ff7c4fa890d7547
MD5 b3a360c1e9edbfb2436f757ddafb92e9
BLAKE2b-256 de1dd4e26c3665d475f630efef06a71cd49cd62a0a5b6c390010c2ea18a79396

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page