console.ts 1.3 KB
Newer Older
fxy060608's avatar
fxy060608 已提交
1
import MagicString from 'magic-string'
fxy060608's avatar
fxy060608 已提交
2
import { normalizePath } from '../utils'
fxy060608's avatar
fxy060608 已提交
3

fxy060608's avatar
fxy060608 已提交
4
export function rewriteConsoleExpr(
fxy060608's avatar
fxy060608 已提交
5
  method: string,
fxy060608's avatar
fxy060608 已提交
6 7 8 9 10
  id: string,
  filename: string,
  code: string,
  sourceMap: boolean = false
) {
fxy060608's avatar
fxy060608 已提交
11
  filename = normalizePath(filename)
fxy060608's avatar
fxy060608 已提交
12 13 14 15 16 17 18 19 20
  const re = /(console\.(log|info|debug|warn|error))\(([^)]+)\)/g
  const locate = getLocator(code)
  const s = new MagicString(code)
  let match: RegExpExecArray | null
  while ((match = re.exec(code))) {
    const [, expr, type] = match
    s.overwrite(
      match.index,
      match.index + expr.length + 1,
fxy060608's avatar
fxy060608 已提交
21
      method + `('${type}','at ${filename}:${locate(match.index).line + 1}',`
fxy060608's avatar
fxy060608 已提交
22 23
    )
  }
fxy060608's avatar
fxy060608 已提交
24 25 26 27
  return {
    code: s.toString(),
    map: sourceMap ? s.generateMap({ source: id, hires: true }) : null,
  }
fxy060608's avatar
fxy060608 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
}

function getLocator(source: string) {
  const originalLines = source.split('\n')
  const lineOffsets: number[] = []

  for (let i = 0, pos = 0; i < originalLines.length; i++) {
    lineOffsets.push(pos)
    pos += originalLines[i].length + 1
  }

  return function locate(index: number) {
    let i = 0
    let j = lineOffsets.length
    while (i < j) {
      const m = (i + j) >> 1
      if (index < lineOffsets[m]) {
        j = m
      } else {
        i = m + 1
      }
    }
    const line = i - 1
    const column = index - lineOffsets[line]
    return { line, column }
  }
}