twoslash
twoslash copied to clipboard
Resolving types from nested `node_modules`
👋 I am using Shiki Twoslash for my new blog (example, code) and I love it! Thank you.
I want each blog post to have its own package.json
so I don't have to add all of the @types
packages required by my code samples to the root package.json
. For example, the code samples in posts/my-first-post/index.md
should use @types
defined in posts/my-first-post/node_modules
. However, when I try to do this it seems that Twoslash is unable to resolve types from nested node_modules
folders.
I've created a reduced test case here: https://github.com/OliverJAsh/twoslash-nested-projects-test
Steps to reproduce:
- Clone the reduced test case and install all dependencies
- Run Twoslash to compile
posts/my-first-post/index.md
- Inspect the output at
posts/my-first-post/render/index.html
yarn
(cd posts/my-first-post && yarn)
twoslash posts/my-first-post posts/my-first-post/render
open posts/my-first-post/render/index.html
In the output we will see the following error:
Cannot find module 'express' or its corresponding type declarations.
This is despite the fact that @types/express
is installed in posts/my-first-post/node_modules
, which is in the same folder as the Markdown file we're compiling.
I can fix the error if I install @types/express
in the root package.json
, but I don't want to do that as described above.
I suspect the reason this happens is because the virtual TS file created by Twoslash has a path outside of the folder posts/my-first-post
?
Yeah, I think the 'find node_modules' resolver in the current shiki-twoslash to be quite naive (likely because I've only used it in a few repos and they've all largely had the root repo) - totally open to that expanding 👍🏻
Thanks for your response! I can try to do this myself but firstly I'd like to get your thoughts on how we should address this. Should it just find @types
in any node_modules
folders that exist in parent folders relative to the Markdown file that contains the code sample?
Yeah, I'd try have have the backwards searching node resolution strategy start from the folder with the markdown inside it. It's a little hard to know how that affects everything, I'd imagine twoslash now needs knowledge about the current dir. and not just pwd, shiki-twoslash probably needs info of the current file also and maybe some of the larger tools might have to pass it in