Django Webpack Loader

3.2.3 · active · verified Sun Apr 12

Django Webpack Loader transparently integrates Webpack-generated frontend assets (JavaScript, CSS, images, etc.) into Django templates. It achieves this by consuming a `webpack-stats.json` file, which is typically generated by the `webpack-bundle-tracker` plugin. The library is actively maintained, currently at version 3.2.3, and generally aligns its compatibility with Django and Node.js LTS releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the essential Django `settings.py` configuration for `django-webpack-loader` and an example of its usage within a Django template. It defines `INSTALLED_APPS`, `STATICFILES_DIRS` to tell Django where static assets are located, and the `WEBPACK_LOADER` dictionary, which points to the `webpack-stats.json` file and specifies the bundle output directory. A minimal `webpack.config.js` setup is also provided as context, showing how to configure `webpack-bundle-tracker` to generate the necessary `webpack-stats.json` file. Remember that `webpack-bundle-tracker` must be separately installed and configured in your Webpack build process.

import os

# settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

INSTALLED_APPS = [
    # ... other Django apps
    'webpack_loader',
]

STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'assets'), # Where your frontend source and webpack bundles might live
)

WEBPACK_LOADER = {
    'DEFAULT': {
        'BUNDLE_DIR_NAME': 'webpack_bundles/', # Webpack output directory within STATICFILES_DIRS
        'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), # Path to webpack-stats.json
        'POLL_INTERVAL': 0.1, # Optional: Poll interval for stats file changes in dev mode (default 0.1s)
        'TIMEOUT': 10, # Optional: Timeout for webpack compilation in dev mode (default 0, never timeouts)
        'CACHE': not DEBUG, # Cache results in production
        'PUBLIC_PATH': '/static/webpack_bundles/', # Typically matches output.publicPath in webpack config
    }
}

# myapp/templates/myapp/index.html
# {% load render_bundle from webpack_loader %}
# <!DOCTYPE html>
# <html>
# <head>
#     <title>My Django App</title>
#     {% render_bundle 'main' 'css' %}
# </head>
# <body>
#     <div id="app"></div>
#     {% render_bundle 'main' 'js' %}
# </body>
# </html>

# Corresponding minimal webpack.config.js snippet (requires webpack-bundle-tracker):
# const path = require('path');
# const BundleTracker = require('webpack-bundle-tracker');
#
# module.exports = {
#   context: __dirname,
#   entry: './assets/js/index.js',
#   output: {
#     path: path.resolve('./assets/webpack_bundles/'),
#     filename: '[name]-[contenthash].js',
#     publicPath: '/static/webpack_bundles/',
#   },
#   plugins: [
#     new BundleTracker({ filename: './webpack-stats.json' }),
#   ],
# };

view raw JSON →