kevin940726 / remark-code-import

đź“ť Populate code blocks from files
https://npm.im/remark-code-import
MIT License
63 stars 11 forks source link

Watch for file changes in Gatsby? #18

Open benallfree opened 2 years ago

benallfree commented 2 years ago

Hello, I'm really enjoying using your remark plugins with Gatsby.

One thing I've noticed is that Gatsby is not aware that changes to the dependent file should rebuild the mdx.

Example:

// Hello.js
console.log('Hello world!')
// test.mdx

```js file=./Hello.js


Changing the contents of `Hello.js` should cause `test.mdx` to rebuild, but unfortunately it does not. Same problem with `remark-codesandbox`.

Any thoughts on this?
kevin940726 commented 2 years ago

TBH, I don't know! I also suffered from this when working with MDX and Next.js. It seems to me that the framework needs to provide some sort of API to allow hot reload this on the library level. I'm guessing that gatsby-source-filesystem does this under the hood but I haven't tested it. Maybe try using adding gatsby-source-filesystem to watch for changes in your imported code? I'll have to get back to this once I have more time to test the integrations.

benallfree commented 2 years ago

At least in the case of Gatsby my solution was to write a custom webpack loader and insert an import at the top of the AST:

import Sandbox001 from “!!my-loader!./Hello.js”

Then Sandbox001 is a module.exports containing the raw code and a codesandbox URL. From there I can modify the AST to show the code and a button or whatever I decide.

Gatsby seems mostly happy with this and webpack picks up changes to the file. There are still frequent misses though, where we pack’s HMR rebuilds the import module but the mdx doesn’t rebuild. Still investigating that part :)

Here are the packages I made if you want any inspiration https://github.com/benallfree/react-babylonjs/tree/demos-1/devtool