How to add sourcemap in React Native for Production?

For source mapping here is the way I go about it:

In my bundle command for my production build I tell it to generate a source map:

iOS:

react-native bundle --platform ios --entry-file index.ios.js --dev false --bundle-output ./ios/main.jsbundle --assets-dest ./ios --sourcemap-output ./sourcemap.js

Android – I had to actually modify the android/app/react.gradle file to get source maps generating on release compile. There might be an easier way but basically you find where it builds up the bundle command in the bundleReleaseJsAndAssets method and add the source map bit to it:

if (Os.isFamily(Os.FAMILY_WINDOWS)) {
    commandLine "cmd","/c", "react-native", "bundle", "--platform", "android", "--dev", "false", "--entry-file",
        entryFile, "--bundle-output", jsBundleFileRelease, "--assets-dest", resourcesDirRelease, "--sourcemap-output", file("$buildDir/../../../sourcemap.js")
} else {
    commandLine "react-native", "bundle", "--platform", "android", "--dev", "false", "--entry-file",
        entryFile, "--bundle-output", jsBundleFileRelease, "--assets-dest", resourcesDirRelease, "--sourcemap-output", file("$buildDir/../../../sourcemap.js")
}

The output path looks a bit odd but that puts it at your root level (same spot as iOS. I wanted it that way. You can obviously put it anywhere).

Then once you have an error with the line number that means nothing you run it through the “source-map” NPM package. You could probably get very elaborate with your approach but I simply went with:

var sourceMap = require('source-map');
var fs = require('fs');

fs.readFile('./sourcemap.js', 'utf8', function (err, data) {
    var smc = new sourceMap.SourceMapConsumer(data);

    console.log(smc.originalPositionFor({
        line: 16,
        column: 29356
    }));
});

Where line and column should be replaced withe line and column number from your example output above.

This obviously works best if you have the source maps stored somewhere as the line and column numbers change from build to build as your code changes. It should get pretty close though if you can use you source control setup of choice to go back to the commit that was used to build the app in question and re-generate the bundle with the additional bits to the command to generate the source map.

Leave a Comment