Created
July 7, 2014 17:01
-
-
Save danxshap/193a74609291150c216d to your computer and use it in GitHub Desktop.
Sass sourcemaps with django-pipeline in local development environment
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
import re | |
import simplejson | |
from pipeline.compilers.sass import SASSCompiler | |
from django.conf import settings | |
class SASSWithSourcemapsCompiler(SASSCompiler): | |
""" | |
For sourcemaps to work properly, we need to replace paths like these: | |
../../../../lessons/static/lessons/course/scss/paid_unit_list | |
with valid local static URLs. So on every request in development we open up the sourcemap file and regex-replace | |
the prefix with our static URL prefix. | |
""" | |
REPLACE_REGEX = re.compile(r'(\.\./)+\D+/static/') | |
def match_file(self, filename): | |
return filename.endswith(('.scss', '.sass')) | |
def compile_file(self, infile, outfile, *args, **kwargs): | |
command_result = None | |
# We only compile Sass via Pipline in production | |
# In development, we use "sass --sourcemap --watch XYZ" so the compilation doesn't run on every request | |
if not settings.DEBUG: | |
command_result = super(SASSWithSourcemapsCompiler, self).compile_file(infile, outfile, *args, **kwargs) | |
# In development, we assume a sourcemap file exists in the same directory as the Sass file | |
# Now we need to rewrite the source URLs so things work nicely in DevTools | |
if settings.DEBUG: | |
sourcemap_path = outfile + '.map' | |
sourcemap_file = open(sourcemap_path, 'r+') | |
sourcemap = simplejson.load(sourcemap_file) | |
# The line that matters | |
sourcemap['sources'] = [self.REPLACE_REGEX.sub(settings.STATIC_URL, sass_partial_url) | |
for sass_partial_url in sourcemap['sources']] | |
sourcemap_file.seek(0) | |
simplejson.dump(sourcemap, sourcemap_file) | |
sourcemap_file.truncate() | |
sourcemap_file.close() | |
return command_result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment