←back to thread

287 points jamesbvaughan | 1 comments | | HN request time: 0.237s | source
Show context
jitl ◴[] No.41086255[source]
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.
replies(2): >>41086718 #>>41092525 #
1. me_vinayakakv ◴[] No.41092525[source]
Funnily, 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!