1 | const path = require('path')
|
2 | const cache = require('lru-cache')(100)
|
3 | const hash = require('hash-sum')
|
4 | const compiler = require('./template-compiler/compiler')
|
5 | const SourceMapGenerator = require('source-map').SourceMapGenerator
|
6 |
|
7 | const splitRE = /\r?\n/g
|
8 | const emptyRE = /^(?:\/\/)?\s*$/
|
9 |
|
10 | module.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 |
|
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 |
|
46 | function 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 | }
|