3 ms·
Pro-tip for embedding JS in an HTML string in a Typescript file: you can get full typecheck etc for your embedded JS snippet if you write it as a top-level func
by jitl 2y ago
Pro-tip for embedding JS in an HTML string in a Typescript file: you can get full typecheck etc for your embedded JS snippet if you write it as a top-level function in your file, and then interpolate the function into your template.
This works because function.toString() in modern runtimes gives you back fully parse-able input source.
You need to make sure you don’t reference anything outside the function, but it’s generally nicer overall than JS-in-string.
Then you treat it as an IIFE. Example:
function globalJS() { document.write('hi') }
const html = `<script>(${globalJS})()</script>`
I use this technique for calling AppleScript-flavored-JS from NodeJS too.
- jamesbvaughan 2y ago> This works because function.toString() in modern runtimes gives you back fully parse-able input source. TIL - that is good to know. I'll probably leave the post as-is but I will use that in the future.
- me_vinayakakv 2y agoFunnily, I had a backend function that used `window`, which was then sent to frontend in this way. I think the project's tsconfig `lib` included `dom` for it to work. Overall a nice technique!