Aller au contenu

Storage

JS

JSBundler

compile() staticmethod

Bundle js files with the javascript bundler for production.

Source code in staticfiles/processors.py
@staticmethod
def compile():
    """Bundle js files with the javascript bundler for production."""
    process = subprocess.Popen(["npm", "run", "compile"])
    process.wait()
    if process.returncode:
        raise RuntimeError(f"Bundler failed with returncode {process.returncode}")

runserver() staticmethod

Bundle js files automatically in background when called in debug mode.

Source code in staticfiles/processors.py
@staticmethod
def runserver() -> subprocess.Popen:
    """Bundle js files automatically in background when called in debug mode."""
    logging.getLogger("django").info("Running javascript bundling server")
    return subprocess.Popen(["npm", "run", "serve"])

Scss

compile(files) staticmethod

Compile scss files to css files.

Source code in staticfiles/processors.py
@staticmethod
def compile(files: CompileArg | Iterable[CompileArg]):
    """Compile scss files to css files."""
    # Generate files inside the generated folder
    # .css files respects the hierarchy in the static folder it was found
    # This converts arg.absolute -> generated/{arg.relative}.scss
    # Example:
    #   app/static/foo.scss          -> generated/foo.css
    #   app/static/bar/foo.scss      -> generated/bar/foo.css
    #   custom/location/bar/foo.scss -> generated/bar/foo.css
    if isinstance(files, Scss.CompileArg):
        files = [files]

    base_args = {"output_style": "compressed", "precision": settings.SASS_PRECISION}

    compiled_files = {
        file.relative.with_suffix(".css"): sass.compile(
            filename=str(file.absolute), **base_args
        )
        for file in files
    }
    for file, content in compiled_files.items():
        dest = GENERATED_ROOT / file
        dest.parent.mkdir(exist_ok=True, parents=True)
        dest.write_text(content)

ManifestPostProcessingStorage

Bases: ManifestStaticFilesStorage

url(name, *, force=False)

Get the URL for a file, convert .scss calls to .css calls to bundled files to their output ones

Source code in staticfiles/storage.py
def url(self, name: str, *, force: bool = False) -> str:
    """Get the URL for a file, convert .scss calls to .css calls to bundled files to their output ones"""
    # This name swap has to be done here
    # Otherwise, the manifest isn't aware of the file and can't work properly
    if settings.DEBUG:
        # In production, the bundler manifest is used at compile time, we don't need to convert anything
        try:
            manifest = JSBundler.get_manifest()
        except FileNotFoundError as e:
            raise Exception(
                "Error loading manifest file, the bundler seems to be busy"
            ) from e
        converted = manifest.mapping.get(name, None)
        if converted:
            name = converted

    path = Path(name)
    if path.suffix == ".scss":
        # Compile scss files automatically in debug mode
        if settings.DEBUG:
            Scss.compile(
                [
                    Scss.CompileArg(absolute=Path(p), relative=Path(name))
                    for p in find(name, all=True)
                ]
            )
        name = str(path.with_suffix(".css"))

    return super().url(name, force=force)