Vue 反編譯 dist 包到源碼
作者:ws_qy
https://juejin.cn/post/7359893196439207972
最近由於公司老項目上的問題,由於項目很老,之前交接的源碼包中缺少了很大一部分模塊,但是現在線上的環境和 dist 包是正常運行的,領導希望能夠手動將這部分補全,由於前期項目的不規範,缺少接口文檔以及原型圖,因此無法知道到底該如何補全,因此,我想着能不能通過 dist 包去反編譯源碼包呢,經過多方面探索發現是可行的,但是隻能編譯出 vue 文件,但是也滿足基本需要了。
1. 如何反編譯
-
首先需要在管理員模式下打開 cmd
-
找到需要編譯的 dist/static/js 的目錄下 執行完成後在該目錄會看到目錄下存在下面的文件名:0.7ab7d1434ffcc747c1ca.js.map,這裏以 0.7ab7d1434ffcc747c1ca.js.map 爲例,如下圖:
- 全局安裝 reverse-sourcemap 資源
npm install --global reverse-sourcemap
- 反編譯 執行:reverse-sourcemap --output-dir source 0.7ab7d1434ffcc747c1ca.js.map
2. 腳本反編譯
上面的方式執行完畢,確實在 source 中會出現源碼,那麼有沒有可能用腳本去執行呢,通過 node 的 child_process 模塊中的 exec 方式便可以執行 reverse-sourcemap --output-dir source 這個命令,那麼只需要拿到當前文件夾中包含. map 文件即可,那麼可以藉助 node 中 fs 模塊,遞歸讀取文件名,並使用正則將所有. map 的文件提取出來放在一個集合或數組中,在對數組進行遞歸循環執行 reverse-sourcemap --output-dir source 這個命令
2.1 根據 child_process 模塊編寫執行函數
function executeReverseSourceMap(outputDir) {
// 構建 reverse-sourcemap 命令
const command = `reverse-sourcemap --output-dir source ${outputDir}`;
// 執行命令
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`執行命令時出錯:${error.message}`);
return;
}
if (stderr) {
console.error(`命令輸出錯誤:${stderr}`);
return;
}
console.log(`命令輸出結果:${stdout}`);
});
}
2.2 讀取文件並匹配文件
// // 讀取文件夾中的文件
fs.readdir(folderPath, (err, files) => {
if (err) {
console.error('讀取文件夾時出錯:', err);
return;
}
// 遍歷文件
files.forEach(file => {
// 使用正則表達式匹配特定格式的文件名
const match = /^(\d+)\..+\.js\.map$/.exec(file);
if (match) {
// 如果匹配成功,將文件名存入數組
targetFiles.push(match[0]);
}
});
// 輸出目標文件名數組
targetFiles.forEach(file=>{
executeReverseSourceMap(file)
})
});
2.3 完整的執行代碼
const fs = require('fs');
const path = require('path');
const { exec } = require('child_process');
// 文件夾路徑
const folderPath = '../js';
// 存放目標文件名的數組
const targetFiles = [];
function executeReverseSourceMap(outputDir) {
// 構建 reverse-sourcemap 命令
const command = `reverse-sourcemap --output-dir source ${outputDir}`;
// 執行命令
exec(command, (error, stdout, stderr) => {
if (error) {
console.error(`執行命令時出錯:${error.message}`);
return;
}
if (stderr) {
console.error(`命令輸出錯誤:${stderr}`);
return;
}
console.log(`命令輸出結果:${stdout}`);
});
}
// // 讀取文件夾中的文件
fs.readdir(folderPath, (err, files) => {
if (err) {
console.error('讀取文件夾時出錯:', err);
return;
}
// 遍歷文件
files.forEach(file => {
// 使用正則表達式匹配特定格式的文件名
const match = /^(?:\w+\.)?(\w+)\.\w+\.js\.map$/.exec(file);
console.log(match);
if (match) {
// 如果匹配成功,將文件名存入數組
targetFiles.push(match[0]);
}
});
// 輸出目標文件名數組
targetFiles.forEach(file=>{
executeReverseSourceMap(file)
})
});
3 最終結果展示圖
本文由 Readfog 進行 AMP 轉碼,版權歸原作者所有。
來源:https://mp.weixin.qq.com/s/neqU4JR1rqv0M1LpLt3EYA