Last active
August 20, 2018 22:22
-
-
Save balazs-endresz/d18621a7fe93b0352e4a015fd9b2058e to your computer and use it in GitHub Desktop.
ManifestStaticFilesStorage with source maps, and ignoring missing files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.contrib.staticfiles.storage import ManifestStaticFilesStorage | |
class ManifestStaticFilesStorageWithSourceMaps(ManifestStaticFilesStorage): | |
""" | |
Adds js and css source map support for ManifestStaticFilesStorage. | |
""" | |
patterns = ( | |
("*.css", ( | |
# django uses only the first two patterns by default: | |
r"""(url\(['"]{0,1}\s*(.*?)["']{0,1}\))""", | |
(r"""(@import\s*["']\s*(.*?)["'])""", """@import url("%s")"""), | |
(r"""(/\*#\s*sourceMappingURL=(.*)\s*\*/)""", """/*# sourceMappingURL=%s */"""), | |
)), | |
("*.js", ( | |
(r"""(//#\s*sourceMappingURL=(.*)$)""", """//# sourceMappingURL=%s"""), | |
)), | |
# .js.map files can contain filenames too that might have to be hashed as well: | |
# ("*.js.map", ( | |
# (r"""([^/]+/static/dist/js/([^"]*))""", """%s""") | |
# )), | |
) | |
def __init__(self, *args, **kwargs): | |
self.missing_files = [] | |
super().__init__(*args, **kwargs) | |
def hashed_name(self, name, *args, **kwargs): | |
""" | |
Ignore missing files, e.g. non-existent background image referenced from css. | |
Returns the original filename if the referenced file doesn't exist. | |
""" | |
try: | |
return super().hashed_name(name, *args, **kwargs) | |
except ValueError as e: | |
message = e.args[0].split(' with ')[0] | |
self.missing_files.append(message) | |
print(f'\x1b[0;30;41m{message}\x1b[0m') | |
return name | |
def post_process(self, *args, **kwargs): | |
yield from super().post_process(*args, **kwargs) | |
for message in sorted(set(self.missing_files)): | |
print(f'\x1b[0;30;41m{message}\x1b[0m') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment