Skip to content

Instantly share code, notes, and snippets.

@loraxx753
Last active December 7, 2023 15:21
Show Gist options
  • Save loraxx753/05e86f51e16b705e1c4ae0c953a8c9c5 to your computer and use it in GitHub Desktop.
Save loraxx753/05e86f51e16b705e1c4ae0c953a8c9c5 to your computer and use it in GitHub Desktop.
./modify-component.js "<file_contents>" -c state -p "New Prop Value"
#!/usr/bin/env node
const fs = require('fs');
const commander = require('commander');
const { program } = commander;
const { init, parse } = require('es-module-lexer');
const vm = require('vm');
// Define your custom module loader and manipulation logic here (as shown in previous examples).
program
.argument('<fileContents>', 'File contents before modification')
.option('-c, --command <command>', 'Modification command')
.option('-p, --propValue <propValue>', 'New prop value for state modification');
program.parse(process.argv);
async function main() {
const { fileContents, command, propValue } = program.opts();
// Initialize the module lexer
await init();
// Create a context to evaluate the module code
const context = { exports: {} };
// Run the module code with the provided file contents in the context
vm.runInContext(fileContents, context, { filename: 'YourComponent.tsx' });
// Apply modifications based on the command
if (command === 'state') {
// Example: Modify the component's state
if (context.exports.default) {
const component = context.exports.default;
if (component.props) {
component.props.someProp = propValue || 'Default Prop Value';
}
}
}
// Serialize the updated exports back into JavaScript module code
const updatedModuleCode = `export default ${JSON.stringify(context.exports)};\n`;
// Print the updated module code (or save it to a file, as needed)
console.log(updatedModuleCode);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment