Skip to content

Instantly share code, notes, and snippets.

@benjie
Created March 6, 2014 10:51
Show Gist options
  • Save benjie/9387284 to your computer and use it in GitHub Desktop.
Save benjie/9387284 to your computer and use it in GitHub Desktop.
Source map support for running CoffeeScript with `coffee`

DIY CoffeeScript source map support

CoffeeScript already has source map support via the -m flag, but you have to compile the .coffee first and then run the .js with node for it to be effective. Running the .coffee directly with coffee seems to have no source map support.

This hack recalculates (and caches in memory) the source map on the fly so it can be imported into the excellent source-map-support module. It's disabled if you run the compiled JS file directly (as you would in production) because it assumes the source maps will already have been generated.

if module.filename.match /\.(lit)?coffee$/
# DIY source map support
require('source-map-support').install
retrieveSourceMap: require './retrieve_source_map'
else
# Assume source maps have already been compiled
require('source-map-support').install()
# Rest of your main file here
coffee = require 'coffee-script'
fs = require 'fs'
cachedSourceMaps = {}
generateSourceMap = (path) ->
return unless path.match /\.(lit)?coffee$/
try
code = fs.readFileSync(path, 'utf8')
options =
filename: path
sourceMap: true
header: false
{js, v3SourceMap} = coffee.compile code, options
v3SourceMap = JSON.parse v3SourceMap
v3SourceMap.file = path
v3SourceMap.sourceRoot = ""
v3SourceMap.sources = [path]
v3SourceMap = JSON.stringify v3SourceMap
cachedSourceMaps[path] = {map: v3SourceMap}
catch e
cachedSourceMaps[path] = null # Prevent recursion
console.error "Error occurred generating sourcemap"
console.error e?.stack
return cachedSourceMaps[path]
module.exports = (path) ->
if typeof cachedSourceMaps[path] isnt 'undefined'
return cachedSourceMaps[path]
else
return generateSourceMap(path)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment