最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

教你巧用webpack在日志中記錄文件行號

 更新時間:2022年11月15日 16:41:28   作者:喬珂力  
早期webpack的目的是允許在瀏覽器中運行大多數(shù)node.js模塊,但是模塊整體格局發(fā)生了變化,現(xiàn)在許多模塊的主要用途是以編寫前端為目的,下面這篇文章主要給大家介紹了關(guān)于巧用webpack在日志中記錄文件行號的相關(guān)資料,需要的朋友可以參考下

前言

在做前端項目時,會在各個關(guān)鍵節(jié)點打印日志,方便后續(xù)數(shù)據(jù)分析和問題排查。當(dāng)日志越來越多之后,又會遇到通過日志反查代碼所在文件和所在行的場景,于是一個很自然的需求就出來了:

在打印日志的時候,自動注入當(dāng)前文件名、行號、列號。

舉個例子,有個 logger 函數(shù),我們在 index.js 的業(yè)務(wù)代碼某一行添加打印邏輯:

const { logLine } = require('./utils')

function getJuejinArticles() {
  const author = 'keliq'
  const level = 'LV.5'
  // ... 業(yè)務(wù)代碼省略,獲取文章列表
  logLine(author, level)
  // ...
}

getJuejinArticles()

正常情況下會輸出:

keliq LV.5

但是希望能夠輸出帶文件名和行號,即:

[index.js:7:3] keliq LV.5

表明當(dāng)前這次打印輸出來源于 index.js 文件中的第 7 行第 3 列代碼,也就是 logLine 函數(shù)所在的具體位置。那如何實現(xiàn)這個需求呢?我的腦海中浮現(xiàn)了兩個思路:

通過提取 Error 錯誤棧

因為 error 錯誤棧里面天然帶有此類信息,可以人工制造了一個 Error,然后捕獲它:

exports.logLine = (...args) => {
  try {
    throw new Error()
  } catch (e) {
    console.log(e.stack)
  }
}

仔細(xì)觀察打印的結(jié)果:

Error
    at logLine (/test/src/utils.js:3:11)
    at getJuejinArticles (/test/src/index.js:7:3)
    at Object.<anonymous> (/test/src/index.js:11:1)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47

第三行的內(nèi)容不正是我們想要的結(jié)果嗎?只需要把這一行的字符串進(jìn)行格式化一下,提取出 index.js:7:3 即可:

at getJuejinArticles (/test/src/index.js:7:3)

由于代碼結(jié)構(gòu)是這樣的:

.
└── src
    ├── index.js
    └── utils.js

只需要改成下面的代碼即可:

exports.logLine = (...args) => {
  try {
    throw new Error()
  } catch (e) {
    const lines = e.stack.split('\n')
    const fileLine = lines[2].split('/src/').pop().slice(0, -1)
    console.log(`[${fileLine}]`, ...args)
  }
}

命令行試一試:

$ test node src/index.js 
[index.js:7:3] keliq LV.5

問題似乎完美解決,然而還是想的太簡單了,上述場景僅限于 node.js 環(huán)境,而在 web 環(huán)境,所有的產(chǎn)物都會被 webpack 打到一個或多個 js 文件里面,而且做了壓縮混淆處理,由于 error 是在運行時被捕獲到的 ,所以我沒根本無法拿到開發(fā)狀態(tài)下的文件名、行號和列號,如下圖所示:

通過 webpack 預(yù)處理

那怎么辦呢?解鈴還須系鈴人,既然 webpack 對代碼進(jìn)行了加工處理,那就只能在預(yù)處理最開始的階段介入進(jìn)來,寫一個自定義的 loader 來解析源碼文件,拿到文件名、行號和列號。說干就干,創(chuàng)建一個 inject-line.loader.js,寫下模板代碼:

module.exports = function (content) {
  content = content.toString('utf-8')
  if (this.cacheable) this.cacheable()
  console.log(this.resourcePath) // 打印文件路徑
  console.log(content) // 打印文件內(nèi)容
  return content
}
module.exports.raw = true

然后在 webpack.config.js 中做配置:

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'index.js',
  },
  module: {
    rules: [
      {
        test: /.js$/,
        exclude: [/node_modules/],
        use: [
          {
            loader: require.resolve('./loaders/inject-line.loader'),
          },
        ],
      },
    ],
  },
}

一切準(zhǔn)備就緒,先運行一下看看輸出:

可以看到,index.js 和 utils.js 被自定義的 inject-line.loader.js 給加載到了,通過 this.resourcePath 能夠拿到文件名稱,行號和列號的話只能通過分析 content 字符串進(jìn)行提取了,處理的代碼如下:

// 拿到文件路徑
const fileName = this.resourcePath.split('/src/').pop()
// 文本內(nèi)容按行處理后再拼接起來
content = content
  .split('\n')
  .map((line, row) => {
    const re = /logLine((.*?))/g
    let result
    let newLine = ''
    let cursor = 0
    while ((result = re.exec(line))) {
      const col = result.index
      newLine += line.slice(cursor, result.index) + `logLine('${fileName}:${row + 1}:${col + 1}', ` + result[1] + ')'
      cursor += col + result[0].length
    }
    newLine += line.slice(cursor)
    return newLine
  })
  .join('\n')

這里面的邏輯,如果光看代碼的話可能會云里霧里,其實思路很簡單,就是下面這樣的:

這樣的話,即使代碼經(jīng)過各種壓縮轉(zhuǎn)換,也不會改變開發(fā)狀態(tài)下代碼所在的文件名、行與列的位置了。打開 webpack 打包后的文件看一下:

到這里,功能就已經(jīng)開發(fā)完了,不過還有一個小小的缺陷就是 logLine 函數(shù)名是寫死的,能不能讓用戶自己定義這個函數(shù)名呢?當(dāng)然可以,在 webpack 配置文件中,支持利用 options 屬性傳遞 config 配置參數(shù):

module.exports = {
  entry: './src/index.js',
  output: {
    filename: 'index.js',
  },
  module: {
    rules: [
      {
        test: /.js$/,
        exclude: [/node_modules/],
        use: [
          {
            loader: require.resolve('./loaders/inject-line.loader'),
            options: {
              config: {
                name: 'customLogName',
              },
            },
          },
        ],
      },
    ],
  },
}

然后在 inject-line.loader.js 代碼中通過 this.query.config 拿到該配置即可,不過正則表達(dá)式也要根據(jù)這個配置動態(tài)創(chuàng)建,字符串替換的時候也要換成該配置變量,最終代碼如下:

module.exports = function (content) {
  content = content.toString('utf-8')
  if (this.cacheable) this.cacheable()
  const { name = 'logLine' } = this.query.config || {}
  const fileName = this.resourcePath.split('/src/').pop()
  content = content
    .split('\n')
    .map((line, row) => {
      const re = new RegExp(`${name}\((.*?)\)`, 'g')
      let result
      let newLine = ''
      let cursor = 0
      while ((result = re.exec(line))) {
        const col = result.index
        newLine += line.slice(cursor, result.index) + `${name}('${fileName}:${row + 1}:${col + 1}', ` + result[1] + ')'
        cursor += col + result[0].length
      }
      newLine += line.slice(cursor)
      return newLine
    })
    .join('\n')

  return content
}
module.exports.raw = true

總結(jié)

到此這篇關(guān)于如何巧用webpack在日志中記錄文件行號的文章就介紹到這了,更多相關(guān)webpack日志記錄文件行號內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

镇平县| 平南县| 岳普湖县| 新余市| 鸡西市| 白河县| 灵武市| 莱西市| 上蔡县| 杨浦区| 巴东县| 伊吾县| 镇坪县| 迭部县| 泾源县| 原阳县| 同心县| 自治县| 长子县| 盈江县| 石河子市| 平阳县| 鱼台县| 小金县| 永城市| 美姑县| 罗源县| 报价| 资溪县| 霍林郭勒市| 铜山县| 大城县| 英吉沙县| 祥云县| 天长市| 江孜县| 拉萨市| 乌拉特后旗| 鹤岗市| 会宁县| 奎屯市|