yarn: cannot find module

Viewed 9180

I have a yarn workspace set up with folders public and server. I am using TypeScript in VS Code. On any module that doesn't have types pre-installed with the package, I get the error in VS Code:

Cannot find module 'x'

However, the IntelliSense will show x as a suggestion. I have both x and @types/x and it seems like it's no difference if I install @types/x. Thanks

Windows 1909 (Latest)
Visual Studio Code 1.43 (Latest)
TypeScript ^3.8.3 (Latest)
Yarn 2.0.0-rc.30 (Latest)

Also, I tried to find type roots for yarn, but didn't. Could someone please tell me where the type root directry is.

3 Answers

Similar issue here. This error is coming from the linter; I think it's checking inside the package lock file (which does not exist as yarn is using yarn.lock).

Please check these in your VSCode user settings.json:

"eslint.packageManager": "yarn",
"prettier.packageManager": "yarn",
"npm.packageManager": "yarn"

These settings have worked for me. YMMV.

EDIT: changed punctuation

Have a look at the instructions here: https://yarnpkg.com/getting-started/editor-sdks

Smart IDEs (such as VSCode or IntelliJ) require special configuration for TypeScript to work. This page intends to be a collection of settings for each editor we've worked with - please contribute to this list!

For example when using a "vscode" IDE execute:

yarn dlx @yarnpkg/pnpify --sdk vscode

The above command will wire up your vscode project to rely on yarn, i.e. it adds the sdks folder within your .yarn config and also tells your IDE to use it, by adding the following to your settings.json:

"typescript.tsdk": ".yarn/sdks/typescript/lib",
"typescript.enablePromptUseWorkspaceTsdk": true

Hint: Yarn caches its packages in form of zip archives. So in order to be also able to inspect your node_modules imports managed by yarn, you can install the ZipFS extension

This extension adds support into VSCode to read files directly from zip archives. It's maintained as part of the Yarn toolchain. Using this extension together with the Yarn SDK will allow you to seamlessly open & edit files from your cache.

From the docs:

To support features like go-to-definition a plugin like ZipFS is needed.

  1. Run the following command, which will generate a new directory called .yarn/sdks:

    yarn dlx @yarnpkg/sdks vscode
    
  2. For safety reason VSCode requires you to explicitly activate the custom TS settings:

  3. Press ctrl+shift+p in a TypeScript file

  4. Choose "Select TypeScript Version"

  5. Pick "Use Workspace Version"

Related