Skip to content

Instantly share code, notes, and snippets.

@jonoirwinrsa
Created February 16, 2019 15:18
Show Gist options
  • Save jonoirwinrsa/91be10b20159b02a1fef01adc02ad5f7 to your computer and use it in GitHub Desktop.
Save jonoirwinrsa/91be10b20159b02a1fef01adc02ad5f7 to your computer and use it in GitHub Desktop.
Upload Create React App sourcemaps to Bugsnag - Complete
const { upload } = require('bugsnag-sourcemaps');
const glob = require('glob');
const fs = require('fs');
const appVersion = require('./package.json').version;
const reportBuild = require('bugsnag-build-reporter');
/**
* Find all of the map files in ./build
*/
function findSourceMaps(callback) {
return glob('build/**/*/*.map', callback);
}
/**
* Uploads the source map with accompanying sources
* @param sourceMap - single .map file
* @returns {Promise<string>} - upload to Bugsnag
*/
function uploadSourceMap(sourceMap) {
// Remove .map from the file to get the js filename
const minifiedFile = sourceMap.replace('.map', '');
// Remove absolute path to the static assets folder
const minifiedFileRelativePath = minifiedFile.split('build/')[1];
return upload({
apiKey: process.env.REACT_APP_BUGSNAG_API_KEY,
appVersion: appVersion,
overwrite: true,
minifiedUrl: `http*://${process.env.REACT_APP_SITE_HOSTNAME}/${minifiedFileRelativePath}`,
sourceMap,
minifiedFile,
projectRoot: __dirname,
uploadSources: true,
});
}
/**
* Delete the .map files
* We do this to protect our source
* @param files - array of sourcemap files
*/
function deleteFiles(files) {
files.forEach(file => {
const path = `${__dirname}/${file}`;
fs.unlinkSync(path);
});
}
/**
* Notifies Bugsnag of the new release
*/
function notifyRelease() {
reportBuild({
apiKey: process.env.REACT_APP_BUGSNAG_API_KEY,
appVersion,
releaseStage: process.env.REACT_APP_RELEASE_STAGE,
})
.then(() => console.log('Bugsnag build reported'))
.catch(err => console.log('Reporting Bugsnag build failed', err.messsage));
}
/**
* Find, upload and delete Source Maps
*/
function processSourceMaps() {
findSourceMaps((error, files) =>
Promise.all(files.map(uploadSourceMap))
.then(() => {
deleteFiles(files);
notifyRelease();
})
.catch(e => {
console.log(e);
})
);
}
processSourceMaps();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment