Skip to content

Instantly share code, notes, and snippets.

@danxshap
Created July 7, 2014 17:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danxshap/193a74609291150c216d to your computer and use it in GitHub Desktop.
Save danxshap/193a74609291150c216d to your computer and use it in GitHub Desktop.
Sass sourcemaps with django-pipeline in local development environment
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