From c632bfd86eb662d2b02b6fbb08b41a7a9d507de3 Mon Sep 17 00:00:00 2001 From: Toilal Date: Tue, 21 Mar 2017 14:09:17 +0100 Subject: [PATCH] Add support for sourcemap Close #4 --- lib/index.js | 36 ++++++++++++++++++++++++++++++++---- 1 file changed, 32 insertions(+), 4 deletions(-) diff --git a/lib/index.js b/lib/index.js index 0f64271..8524c23 100644 --- a/lib/index.js +++ b/lib/index.js @@ -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, { @@ -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) {