As mentioned in a previous post – I’ve been working on dynamically loading TypeScript/JavaScript as required (i.e. like a runtime plugin system) and whilst investigating the process have come across several libraries that I felt I’d document in case I need them in the future. First up is require-from-string.
I’ll assume for this and any follow up posts, that you’ve created a basic set-up, i.e.
- yarn init –typescript
- tsc –init
Although I’ve added TypeScript in the above, for simplicity we’re going to start out just using JavaScript, but we’ve covered all bases with TypeScript’s inclusion.
Next create an index.js that looks like this
import requireFromString from 'require-from-string'; const classA = requireFromString('class A { output() { console.log("Remote class called") } } module.exports = A;'); new classA().output();