index.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. export default function GvaPosition() {
  2. return {
  3. name: 'gva-position',
  4. apply: 'serve',
  5. transform(code, id) {
  6. const index = id.lastIndexOf('.')
  7. const ext = id.substr(index + 1)
  8. if (ext.toLowerCase() === 'vue') {
  9. return codeLineTrack(code, id)
  10. }
  11. },
  12. }
  13. }
  14. const codeLineTrack = (code, id) => {
  15. const lineList = code.split('\n')
  16. const newList = []
  17. lineList.forEach((item, index) => {
  18. newList.push(addLineAttr(item, index + 1, id)) // 添加位置属性,index+1为具体的代码行号
  19. })
  20. return newList.join('\n')
  21. }
  22. const addLineAttr = (lineStr, line, id) => {
  23. if (!/^\s+</.test(lineStr)) {
  24. return lineStr
  25. }
  26. const reg = /((((^(\s)+\<))|(^\<))[\w-]+)|(<\/template)/g
  27. let leftTagList = lineStr.match(reg)
  28. if (leftTagList) {
  29. leftTagList = Array.from(new Set(leftTagList))
  30. leftTagList.forEach((item) => {
  31. const skip = [
  32. 'KeepAlive',
  33. 'template',
  34. 'keep-alive',
  35. 'transition',
  36. 'el-',
  37. 'El',
  38. 'router-view',
  39. ]
  40. if (item && !skip.some((i) => item.indexOf(i) > -1)) {
  41. const reg = new RegExp(`${item}`)
  42. const location = `${item} code-location="${id}:${line}"`
  43. lineStr = lineStr.replace(reg, location)
  44. }
  45. })
  46. }
  47. return lineStr
  48. }