Skip to content

Commit

Permalink
Add support for sourcemap
Browse files Browse the repository at this point in the history
Close #4
  • Loading branch information
Toilal committed Mar 21, 2017
1 parent 7073491 commit 6653bb9
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 6 deletions.
37 changes: 33 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) {
const sourceMap = require('source-map')
const SourceMapConsumer = sourceMap.SourceMapConsumer
const 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,31 @@ module.exports = function(contents) {
}
})

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

// apply the original sourcemap to the sourcemap generated by escodegen.
const generatedSmc = generatedContents.map.toJSON()
const sourceMapGenerator = SourceMapGenerator.fromSourceMap(generatedSmc)

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

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

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

function genHotReload (id) {
Expand Down
9 changes: 7 additions & 2 deletions test/specs/index.spec.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,18 @@
const path = require('path')
const fs = require('fs')
const loader = require('../../lib/index')
const DefaultLoader = require('../../lib/index')

class Loader extends DefaultLoader {
callback(err, contents, sourcemap) { this.callbackAnswer = { err, contents, sourcemap } }
}

function test (name) {
const src = fs.readFileSync(path.resolve(__dirname, '../fixtures', name), 'utf8')
const expected = fs.readFileSync(path.resolve(__dirname, '../expects', name), 'utf8')

it(name, () => {
expect(loader(src).replace(/if \(module\.hot\)[\s\S]*$/, '').trim()).toBe(expected.trim())
const loader = new Loader(src)
expect(loader.callbackAnswer.contents.replace(/if \(module\.hot\)[\s\S]*$/, '').trim()).toBe(expected.trim())
})
}

Expand Down

0 comments on commit 6653bb9

Please sign in to comment.