• Stars
    star
    237
  • Rank 169,941 (Top 4 %)
  • Language
    JavaScript
  • License
    BSD 3-Clause "New...
  • Created about 12 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Django staticfiles post-processor for optimizing with RequireJS.

django-require

django-require is a Django staticfiles post-processor for optimizing with RequireJS.

Features

  • Optimize your static assets using the excellent r.js optimizer.
  • Compile standalone modules using the almond.js shim.
  • Compatible with any Django staticfiles storage backend.

Installation

  1. Checkout the latest django-require release and copy or symlink the require directory into your PYTHONPATH. If using pip, run pip install django-require.
  2. Add 'require' to your INSTALLED_APPS setting.
  3. Set your STATICFILES_STORAGE setting to 'require.storage.OptimizedStaticFilesStorage', 'require.storage.OptimizedCachedStaticFilesStorage' or 'require.storage.OptimizedManifestStaticFilesStorage'.

Available settings

Available settings, and their default values, are shown below. You should configure this to match the layout of your project's static files. Please consult the RequireJS documentation for more information about how to build javascript using RequireJS.

# The baseUrl to pass to the r.js optimizer, relative to STATIC_ROOT.
REQUIRE_BASE_URL = "js"

# The name of a build profile to use for your project, relative to REQUIRE_BASE_URL.
# A sensible value would be 'app.build.js'. Leave blank to use the built-in default build profile.
# Set to False to disable running the default profile (e.g. if only using it to build Standalone
# Modules)
REQUIRE_BUILD_PROFILE = None

# The name of the require.js script used by your project, relative to REQUIRE_BASE_URL.
REQUIRE_JS = "require.js"

# A dictionary of standalone modules to build with almond.js.
# See the section on Standalone Modules, below.
REQUIRE_STANDALONE_MODULES = {}

# Whether to run django-require in debug mode.
REQUIRE_DEBUG = settings.DEBUG

# A tuple of files to exclude from the compilation result of r.js.
REQUIRE_EXCLUDE = ("build.txt",)

# The execution environment in which to run r.js: auto, node or rhino.
# auto will auto-detect the environment and make use of node if available and rhino if not.
# It can also be a path to a custom class that subclasses
# require.environments.Environment and defines some "args" function that
# returns a list with the command arguments to execute.
REQUIRE_ENVIRONMENT = "auto"

Generating require.js

As a shortcut to downloading a copy of require.js from the internet, you can simply run the require_init management to copy a version of require.js into your STATICFILES_DIRS, at the location specified by your REQUIRE_BASE_URL and REQUIRE_JS settings.

$ ./manage.py require_init

Generating build profiles

In almost all cases, you'll want to create a custom build profile for your project. To help you get started, django-require can generate a default build profile into your STATICFILES_DIRS. Just set your REQUIRE_BUILD_PROFILE setting to a build profile name, and run require_init. A good name for a build profile would be 'app.build.js'.

Any standalone modules that your specify with a build profile will also have a default build profile generated when you run this command.

Running javascript modules in templates

You can run javascript modules in templates by using the {% require_module %} template tag.

<html>
    {% load require %}
    <head>
        {% require_module 'main' %}
    </head>
    <body></body>
</html>

This template fragment would then render to something like:

<html>
    <head>
        <script src="/static/js/require.js" data-main="/static/js/main.js"></script>
    </head>
    <body></body>
</html>

If the 'main' module was specified as a standalone module in your REQUIRE_STANDALONE_MODULES setting, and REQUIRE_DEBUG is False, then the template fragment would instead render as:

This template fragment would then render to something like:

<html>
    <head>
        <script src="/static/js/main-built.js"></script>
    </head>
    <body></body>
</html>

Building standalone modules

As a further optimization to your code, you can build your modules to run independently of require.js, which can often speed up page load times. Standalone modules are built using the almond.js shim, so consult the almond.js documentation to make sure that it's safe to build your module in standalone mode.

To specify standalone modules, simply add them to your REQUIRE_STANDALONE_MODULES setting, as below:

REQUIRE_STANDALONE_MODULES = {
    "main": {
        # Where to output the built module, relative to REQUIRE_BASE_URL.
        "out": "main-built.js",

        # Optional: A build profile used to build this standalone module.
        "build_profile": "main.build.js",
    }
}

Running the r.js optimizer

The r.js optimizer is run automatically whenever you call the collectstatic management command. The optimizer is run as a post-processing step on your static files.

django-require provides three storage classes that are ready to use with the r.js optimizer:

  • require.storage.OptimizedStaticFilesStorage - A filesystem-based storage that runs the r.js optimizer.
  • require.storage.OptimizedCachedStaticFilesStorage - As above, but fingerprints all files with an MD5 hash of their contents for HTTP cache-busting.
  • require.storage.OptimizedManifestStaticFilesStorage - As above, but fingerprints all files with an MD5 hash of their contents for HTTP cache-busting and stores the fingerprints in a JSON file on disk instead of using a cache. Please note that the OptimizedManifestStaticFilesStorage is only available in Django 1.7 and above.

Creating your own optimizing storage classes

You can add r.js optimization to any Django staticfiles storage class by using the require.storage.OptimizedFilesMixin. For example, to make an optimizing storage that uploads to Amazon S3 using S3BotoStorage from django-storages:

from storages.backends.s3boto import S3BotoStorage
from require.storage import OptimizedFilesMixin

# S3 storage with r.js optimization.
class OptimizedS3BotoStorage(OptimizedFilesMixin, S3BotoStorage):
    pass

# S3 storage with r.js optimization and MD5 fingerprinting.
from django.contrib.staticfiles.storage import CachedFilesMixin
class OptimizedCachedS3BotoStorage(OptimizedFilesMixin, CachedFilesMixin, S3BotoStorage):
    pass

For ready-made storage classes that combine django-require with Amazon S3, check out django-require-s3.

Other projects extending django-require

Tests

You can run the test suite from the root of the source checkout:

test_project/manage.py test require

Test coverage reports can be generated from the same directory with:

coverage run --source='.' test_project/manage.py test require
coverage html

Open htmlcov/index.html in a browser to see the HTML coverage report.

Support and announcements

Downloads and bug tracking can be found at the main project website.

You can keep up to date with the latest announcements by joining the django-require discussion group.

More information

The django-require project was developed by Dave Hall. You can get the code from the django-require project site.

Dave Hall is a freelance web developer, based in Cambridge, UK. You can usually find him on the Internet in a number of different places:

More Repositories

1

django-reversion

django-reversion is an extension to the Django web framework that provides version control for model instances.
Python
2,969
star
2

html5media

Enables <video> and <audio> tags in all major browsers.
JavaScript
1,276
star
3

django-watson

Full-text multi-table search application for Django. Easy to install and use, with good performance.
Python
1,187
star
4

django-herokuapp

A set of utilities and a project template for running Django sites on Heroku.
Python
429
star
5

django-s3-storage

Django Amazon S3 file storage.
Python
407
star
6

django-python3-ldap

Django LDAP user authentication backend for Python 3.
Python
398
star
7

aiohttp-wsgi

WSGI adapter for aiohttp.
Python
231
star
8

logot

Test whether your code is logging correctly 🪵
Python
89
star
9

cms

A collection of Django extensions that add content-management facilities to Django projects.
Python
40
star
10

django-historylinks

Automatic SEO-friendly HTTP 301 redirects if the URL of a model changes.
Python
37
star
11

django-usertools

A fire-and-forget enhancement to the Django user admin
Python
32
star
12

django-optimizations

A utility library for Django aimed at improving website performance
Python
32
star
13

django-uuid-upload-path

Generate short UUIDs and use them as paths for uploaded media files in Django.
Python
19
star
14

moody-templates

A fast, extensible templating engine for Python 3 with Django-like syntax.
Python
18
star
15

django-subscribers

Python
12
star
16

django-require-s3

An integration between django-require and the S3 storage backend from django-storages.
Python
8
star
17

jquery-showcase

A snazzy little showcase widget, built using jQuery.
JavaScript
5
star
18

py.sh

Install and manage a standalone Python interpreter and dependencies.
Python
4
star
19

requirejs-tpl-angular

AngularJS template loader plugin for RequireJS.
JavaScript
3
star
20

state-machine

Immutable state management for javascript clients and servers.
JavaScript
2
star
21

catcam

Don't want the cat to get up to any shenanigans while we are away...
Python
2
star
22

js-base-error

A base error class with stack trace support.
JavaScript
2
star
23

requirejs-less

LESS stylesheet loader plugin for RequireJS.
JavaScript
2
star
24

js-set

Helpers for using unique sorted arrays as sets.
TypeScript
1
star
25

lowline

A more efficient Cow<str> and Vec<Cow<str>>.
Rust
1
star
26

radiopi

RadioPi control daemon
Python
1
star
27

olaf-the-beheader

OLAF BEHEAD PUNY FILES!
Python
1
star