Evening all!
Still working on this small bootstrap app to create some news files/folders and update other files based on CLI input.
Where I'm stuck at is insert a new import statement into an existing JS file, after the last import statement. I found a very very similar thread, but my code fails on the document.body.innerHTML
with an error telling me document is undefined
.
The file I am reading from is called resoruceType.js
and it has roughly 30 imports for other react components. What I am trying to do, is find the last import, and programmatically add another for the newly created bootstrap component my cli tool is creating.
This is the function I've written to search:
updateResourceType: async function(answers) {
logger.info(`INFO: Adding the new component to the resoruceType.js file`);
// TODO: Add the new import to the global resourceType
String.prototype.splice = function(index, rem, str) {
return this.slice(0, index) + str + this.slice(index + Math.abs(rem));
};
let file = path.join(process.cwd(), process.env.reactRepo, process.env.resourceTypeFile);
let insert = file.lastIndexOf("\nimport ");
insert = file.indexOf("\n", insert+1)
document.body.innerHTML = file.splice(insert+1, 0, `import ${answers.componentName} from ./components/global/${answers.componentName}/${answers.componentName}`)
// TODO: Wrap the below in a read statement to confirm the import statement was added
logger.success(`SUCCESS: Finished adding new import to the resoruceType.js file`);
}
I imagine I can't use document.body.innerHTML
because I'm working with a different file, so I did try changing document
to file
but got the error TypeError: Cannot set properties of undefined (setting 'innerHTML')
I've alternatively been seeing how I can do this with fs.readFileSync
and fs.writeFileSync
, but still working through the right search keywords to help find some good docs.
Hope this helps and would love some thoughts on areas to read up on so I can get it right as I do need to do similar functions like this across a few different files.
As always, really appreciate the extra set of brains and eyes!
Cheers Tim