UNPKG

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