Debug builds from Angular generate a separate source map file for each Javascript file which usually allows you to debug your original source code files.
Unfortunately, out-of-the-box debugging does not work* when attaching to an Android web view (eg with Chrome using chrome://inspect).
A solution to this is to inline source maps with your code. The Angular CLI does not expose an easy way to do this but with a couple of tweaks, you can do this yourself.
In your ionic.config.json file add a hook as below:
{
"name": "my-app",
"integrations": {
"capacitor": {}
},
"type": "angular",
"hooks": {
"build:after": "./inline-source-maps.js"
}
}
Then create a file called inline-source-maps.js:
let fs = require('fs');
let path = require('path');
const TARGET_DIR = 'www';
module.exports = function (ctx) {
if (ctx.argv.includes('--release') || ctx.build.platform !== "android") {
return;
}
let files = fs.readdirSync(TARGET_DIR);
let count = 0;
files.forEach(file => {
let mapFile = path.join(TARGET_DIR, `${file}.map`);
let targetFile = path.join(TARGET_DIR, file);
if (path.extname(file) === '.js' && fs.existsSync(mapFile)) {
let bufMap = fs.readFileSync(mapFile).toString('base64');
let bufFile = fs.readFileSync(targetFile, "utf8");
let result = bufFile.replace(`sourceMappingURL=${file}.map`, 'sourceMappingURL=data:application/json;charset=utf-8;base64,' + bufMap);
fs.writeFileSync(targetFile, result);
fs.unlinkSync(mapFile);
count++;
}
});
};
Now, whenever you run the Ionic command for running with Android:
ionic cap run android
After your application is built it will merge the source map file with the source code and when you run chrome://inspect or edge://inspect in the browser you will be able to see your source code appear under the webpack:// tree as shown below:

Also, note that if you are using Ionic's live reload feature that inline sourcemaps are not necessary. You should be able to run ionic cap run android -l -external and your source maps should be available.
* The reason for failing is that the URL for assets like .js etc loaded are localhost but this is not the host name of the actual device so when the source map tries to load from localhost it fails.
Comments
0 comments
Article is closed for comments.