Nanfeng

Notes on software development, code, and curious ideas

Mapping Cocos Creator Production Errors Back to Source Code

This article continues Global Error Handling in Cocos Creator.

Use case

Errors in an exported Cocos Creator project often point only to minified JavaScript. A stack trace provides clues, but locating the original source can still be difficult.

For example:

1
{"message":"Cannot read properties of null (reading 'length')","stack":"TypeError: Cannot read properties of null (reading 'length')\nat e.getChildByName (https://lengmo714.top/test/cocos-js/cc.7297c.js:1:383931)\nat n.watchTheGame (https://lengmo714.top/test/assets/main/index.fef9f.js:317:57103)"}

This indicates that getChildByName returned null and the application then tried to access its length property.

You could search globally for watchTheGame, but that may not identify the exact call site. Disabling minification can help in local testing, but is generally unsuitable for a production deployment. The recommended approach is to generate source maps.

Enable Source Map during the build so every compiled .js file has a corresponding .map file. Do not publish the maps publicly in production unless that exposure is intentional; keep them available privately for diagnostics.

Install the source-map package:

1
npm install source-map

Create lookupSourceMap.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const fs = require('fs');
const sourceMap = require('source-map');

async function lookup(mapFile, line, column) {
const rawSourceMap = JSON.parse(fs.readFileSync(mapFile, 'utf-8'));
const consumer = await new sourceMap.SourceMapConsumer(rawSourceMap);
const pos = consumer.originalPositionFor({ line, column });
console.log('Original source position:', pos);
consumer.destroy();
}

const [,, mapFile, line, column] = process.argv;
if (!mapFile || !line || !column) {
console.error('Usage: node lookupSourceMap.js path/to/file.js.map line column');
process.exit(1);
}

lookup(mapFile, Number(line), Number(column));

Run it with the generated line and column:

1
node lookupSourceMap.js ./cc.js.map 1 383931

Example output:

1
2
3
4
5
6
Original source position: {
source: 'src/game/watchTheGame.ts',
line: 120,
column: 15,
name: 'watchTheGame'
}

Enable source maps in the Cocos Creator export settings:

Enable Source Map

I also wrapped this lookup in a small utility to avoid entering the command every time:

Before lookup

After lookup

Utility demonstration

Download link 1 · Download link 2

+