Skip to content

Instantly share code, notes, and snippets.

@marclove
Last active December 14, 2015 22:19
Show Gist options
  • Save marclove/5157764 to your computer and use it in GitHub Desktop.
Save marclove/5157764 to your computer and use it in GitHub Desktop.
# Steps to implement:
# 1. Ensure you're using >= coffeescript-1.6.1
#
# 2. Put this file in an initializer.
#
# 3. Edit an environment's config to turn on source maps:
#
# `config.assets.sourcemaps = true`
#
# 4. Add /public/sourcemaps to your .gitignore
#
# 5. Turn on source maps in Google Chrome:
# http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-realworld
require 'tilt/template'
module Tilt
class CoffeeScriptTemplate < Template
def evaluate(scope, locals, &block)
if Rails.configuration.assets.sourcemaps
@output ||= begin
root_filename = scope.pathname.basename.to_s.split('.').first
# Get a relative path of our original Coffeescript file
rel_path = if scope.pathname.to_s.start_with?(Bundler.bundle_path.to_s)
Pathname('bundler').join(scope.pathname.relative_path_from(Bundler.bundle_path)).dirname
else
scope.pathname.relative_path_from(Rails.root).dirname
end
map_files_path = Rails.root.join('public','sourcemaps', rel_path)
map_file_path = map_files_path.join("#{root_filename}.map")
coffee_file_path = map_files_path.join("#{root_filename}.coffee")
FileUtils.mkdir_p(map_files_path) unless File.directory?(map_files_path)
compiled = CoffeeScript.compile(data, options.merge(pathname: scope.pathname, sourceMap:true, filename:"#{root_filename}.coffee"))
# Put the original .coffee file and its map file in /public/sourcemaps/... where the browser can get it
coffee_file_path.open('w') {|f| f.puts data }
map_file_path.open('w') {|f| f.puts compiled["v3SourceMap"]}
# Add the header declaration to the js file, telling browser where to find the mappings files
"//@ sourceMappingURL=/#{map_file_path.relative_path_from(Rails.root.join('public'))}\n\n#{compiled['js']}"
end
else
@output ||= CoffeeScript.compile(data, options)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment