Skip to content

Instantly share code, notes, and snippets.

@arleighdickerson
Created December 12, 2022 19:26
Show Gist options
  • Save arleighdickerson/3491aab0fb0ed54bab5e4dc3751b5300 to your computer and use it in GitHub Desktop.
Save arleighdickerson/3491aab0fb0ed54bab5e4dc3751b5300 to your computer and use it in GitHub Desktop.
a script to make node_modules/reactstrap compatible with preact
// ============================================================================
// patches node_modules/reactstrap for compatibility with preact
// ============================================================================
const glob = require('glob');
const fs = require('fs');
function resolvePath(moduleId = 'reactstrap') {
try {
const resolved = require.resolve(moduleId);
const search = `node_modules/${moduleId}`;
return resolved.substring(0, resolved.indexOf(search) + search.length);
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
console.error(`could not require.resolve('${moduleId}'). Is ${moduleId} actually installed?`);
}
throw e;
}
}
function getFiles(ext = null) {
if (ext === null) {
return Promise.all(['js', 'cjs', 'esm'].map(getFiles)).then(arrays => [].concat(...arrays));
}
const pattern = `${resolvePath()}/**/*.${ext}`;
return new Promise((resolve, reject) => {
glob(pattern, {}, (err, files) => {
if (err) {
reject(err);
} else {
resolve(files);
}
});
});
}
async function doReplace(filename) {
const strip = [`List.name = 'List';`, `ListInlineItem.name = 'ListInlineItem';`];
let contents = await new Promise((resolve, reject) => {
fs.readFile(filename, { encoding: 'utf-8' }, (err, data) => {
if (err) {
reject(err);
} else {
resolve(String(data));
}
});
});
const len = contents.length;
strip.forEach(str => {
contents = contents.replaceAll(str, '');
});
if (contents.length === len) {
return;
}
await new Promise((resolve, reject) => {
fs.writeFile(filename, contents, { encoding: 'utf-8' }, err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
process.on('unhandledRejection', (reason, p) => {
console.error('Unhandled Rejection at: Promise ', p, reason);
process.exit(1);
});
if (require.main === module) {
getFiles()
.then(files => Promise.all(files.map(doReplace)))
.then(() => process.exit(0))
.catch(e => {
console.error(e);
process.exit(1);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment