parser.js 1.5 KB

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