|
1 | 1 | var compiler = require('vue-template-compiler')
|
2 | 2 | var cache = require('lru-cache')(100)
|
3 | 3 | var hash = require('hash-sum')
|
| 4 | +var SourceMapGenerator = require('source-map').SourceMapGenerator |
| 5 | + |
| 6 | +var splitRE = /\r?\n/g |
| 7 | +var emptyRE = /^(?:\/\/)?\s*$/ |
4 | 8 |
|
5 | 9 | module.exports = function (content, filename, needMap) {
|
6 | 10 | var cacheKey = hash(filename + content)
|
7 | 11 | // source-map cache busting for hot-reloadded modules
|
8 | 12 | var filenameWithHash = filename + '?' + cacheKey
|
9 | 13 | var output = cache.get(cacheKey)
|
10 | 14 | if (output) return output
|
11 |
| - output = compiler.parseComponent(content, { |
12 |
| - pad: true, |
13 |
| - map: needMap |
14 |
| - ? { filename: filenameWithHash } |
15 |
| - : false |
16 |
| - }) |
| 15 | + output = compiler.parseComponent(content, { pad: true }) |
| 16 | + if (needMap) { |
| 17 | + if (output.script && !output.script.src) { |
| 18 | + output.script.map = generateSourceMap( |
| 19 | + filenameWithHash, |
| 20 | + content, |
| 21 | + output.script.content |
| 22 | + ) |
| 23 | + } |
| 24 | + if (output.styles) { |
| 25 | + output.styles.forEach(style => { |
| 26 | + if (!style.src) { |
| 27 | + style.map = generateSourceMap( |
| 28 | + filenameWithHash, |
| 29 | + content, |
| 30 | + style.content |
| 31 | + ) |
| 32 | + } |
| 33 | + }) |
| 34 | + } |
| 35 | + } |
17 | 36 | cache.set(cacheKey, output)
|
18 | 37 | return output
|
19 | 38 | }
|
| 39 | + |
| 40 | +function generateSourceMap (filename, source, generated) { |
| 41 | + var map = new SourceMapGenerator() |
| 42 | + map.setSourceContent(filename, source) |
| 43 | + generated.split(splitRE).forEach((line, index) => { |
| 44 | + if (!emptyRE.test(line)) { |
| 45 | + map.addMapping({ |
| 46 | + source: filename, |
| 47 | + original: { |
| 48 | + line: index + 1, |
| 49 | + column: 0 |
| 50 | + }, |
| 51 | + generated: { |
| 52 | + line: index + 1, |
| 53 | + column: 0 |
| 54 | + } |
| 55 | + }) |
| 56 | + } |
| 57 | + }) |
| 58 | + return map.toJSON() |
| 59 | +} |
0 commit comments