pngwn / MDsveX

A markdown preprocessor for Svelte.
https://mdsvex.pngwn.io
MIT License
2.49k stars 105 forks source link

Allow usage of JavaScript defined in mdsvex code blocks for interactivity #608

Open NazCodeland opened 5 months ago

NazCodeland commented 5 months ago

I’m writing a blog post in mdsvex and my article contains JavaScript code blocks. I’d like to be able to use the code within the JavaScript block to provide an interactive illustration of the code. Currently, I have to duplicate the code the script tag to make it interactive which is not ideal.

Here’s an example:

function privateFunction() {
  console.log("This is a private function")
}
<button on:click={privateFunction}>Click me</button>

In this example, I’d like the privateFunction to be callable from the button’s click event without having to also define it in a script tag. This feature would make writing interactive blog posts much easier. Thank you for considering this request!

danbulant commented 3 months ago

you could write a remark plugin to do that for you - mdsvex accepts remarkPlugins array, pass it a function that returns a function accepting arguments tree, file. Tree contains the remark AST, so a node with a string type and some children. You can alter the AST, for example by adding new raw blocks based on the code block/node.

einarpersson commented 2 weeks ago

@NazCodeland Did you solve it with a custom plugin as suggested? If so would be very nice of you to share (or share a link to your interactive blog ;) )