Skip to content

Commit

Permalink
Add support for sourcemap
Browse files Browse the repository at this point in the history
Close ktsn#4
  • Loading branch information
Toilal committed Mar 21, 2017
1 parent 7073491 commit c632bfd
Showing 1 changed file with 32 additions and 4 deletions.
36 changes: 32 additions & 4 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,18 @@ const estraverse = require('estraverse')
const genCode = require('escodegen')
const genId = require('./gen-id')

module.exports = function(contents) {
var sourceMap = require('source-map');
var SourceMapConsumer = sourceMap.SourceMapConsumer;
var SourceMapGenerator = sourceMap.SourceMapGenerator;

module.exports = function(contents, sourcemap) {
const id = genId(this.resourcePath)
let hasComponent = false

const ast = acorn.parse(contents, {
sourceType: 'module'
sourceType: 'module',
locations: true,
sourceFile: this.resourcePath
})

const res = estraverse.replace(ast, {
Expand Down Expand Up @@ -39,8 +45,30 @@ module.exports = function(contents) {
}
})

return genCode.generate(res)
+ (hasComponent ? genHotReload(id) : '')
if (hasComponent) {
if (sourcemap) {
let generatedContents = genCode.generate(res, {
sourceMap: this.resourcePath,
sourceMapWithCode: true,
sourceContent: contents
})

// apply the original sourcemap to the sourcemap generated by escodegen.
let sourceMapGenerator = SourceMapGenerator.fromSourceMap(generatedSmc)

let originalSmc = new SourceMapConsumer(sourcemap)
sourceMapGenerator.applySourceMap(originalSmc)
let outSourcemap = sourceMapGenerator.toJSON()

this.callback(null, generatedContents.code + genHotReload(id), outSourcemap)
} else {
let generatedContents = genCode.generate(res);

this.callback(null, generatedContents + genHotReload(id))
}
} else {
this.callback(null, contents, sourcemap)
}
}

function genHotReload (id) {
Expand Down

0 comments on commit c632bfd

Please sign in to comment.