微信小程序根据线上版本 Source Map 文件定位错误代码

时间:2022-07-25
本文章向大家介绍微信小程序根据线上版本 Source Map 文件定位错误代码,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

话不多说,直接上流程

  1. 将微信后台SoureMap文件下载下来
  1. 解压下载的文件,可得到以下目录

该目录对应的就是我们小程序分包

也就是说,如果我们的页面在packageDynamic包下,我们定位的时候就要使用packageDynamic下的文件

  1. 添加一个定位页面,代码入下,copy过去直接运行即可
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SourceMap 查看工具</title>
    <script src="https://cdn.staticfile.org/jquery/3.4.1/jquery.js"></script>
    <script src="https://unpkg.com/source-map@0.7.3/dist/source-map.js"></script>
    <script>
        sourceMap.SourceMapConsumer.initialize({
            "lib/mappings.wasm": "https://unpkg.com/source-map@0.7.3/lib/mappings.wasm"
        });
    </script>
</head>
<body>
<form id="myForm">
    <p>
        <label for="line-column">line:column </label><input id="line-column" name="line-column">
    </p>
    <p>
        <label for="sourceMapFile">sourceMapFile </label><input id="sourceMapFile" type="file" name="sourceMapFile">
    </p>
    <button type="submit" name="submit">确定</button>
</form>
<table id="result" border="1" cellspacing="0" cellpadding="10">
    <tr>
        <th>line:column</th>
        <th> ==></th>
        <th>source</th>
        <th>line</th>
        <th>column</th>
        <th>name</th>
    </tr>
    <!--<tr>-->
    <!--<td>line:column</td><td> ==> </td><td>line</td><td>column</td><td>source</td><td>name</td>-->
    <!--</tr>-->
</table>
<script>
    $(function () {
        const form = $('#myForm');
        form.on('submit', function (e) {
            e.preventDefault();
            const dataArray = form.serializeArray();
            const dataObj = dataArray.reduce((obj, item) => {
                obj[item.name] = item.value;
                return obj;
            }, {});
            let [line, column] = dataObj['line-column'].split(':');

            // 读取文件
            let file = $('#sourceMapFile').get(0).files[0];
            const fileReader = new FileReader();
            fileReader.onloadend = function () {
                const rawSourceMap = fileReader.result;
                // 查找
                sourceMap.SourceMapConsumer.with(rawSourceMap, null, consumer => {
                    const result = consumer.originalPositionFor({
                        source: "./",
                        line: +line,
                        column: +column
                    });
                    $('#result').append($(`
                        <tr>
                            <td>${line}:${column}</td><td> ==> </td><td>${result.source}</td><td>${result.line}</td><td>${result.column}</td><td>${result.name}</td>
                        </tr>
                    `));
                });
            };
            fileReader.readAsText(file);
            return false;
        });
    });
</script>
</body>
</html>
  1. 运行copy好的代码

看到如下界面就可以开始定位了

  1. 查看小程序后台日志错误提示
  1. 将相应的报错行数复制到工具页面,并选择相应文件夹下的文件即可