yarnpkgyarn-v3

Yarn project is using yarn3x and Plug 'N Play but doesn't work without node_modules directory


I'm trying to create a new NestJS project with Yarn as the package manager. After installing NestJS with npm globally (npm install -g @nestjs/cli), I ran npx nest new [package name] --strict, then selected Yarn as the package manager in the resulting CLI.

A fresh NestJS project is created. I run yarn to install the packages, but every module that the files in the generated project try to import throw Cannot find module

e.g.:

Cannot find module '@nestjs/common' or its corresponding type declarations.

It's only when I tried npm install, which created a node_modules directory, that the imports work. So it appears that the project is using yarn classic/without Plug 'N Play?

However, when I run yarn -v in my home directory, I get 3.3.0, so that should mean the global yarn version is 3.3.0 (if there is such thing as a global yarn version)?

yarn -v inside this new project also gives 3.3.0, and only in another project that I explicitly set to yarn 1x does the command give 1.22.19.

Furthermore, my project does have the .pnp.cjs and .pnp.loader.mjs files. So why is it not working without node_modules?

I even added a .yarnrc.yml file and added this line inside: nodeLinker: "pnp" as per this documentation

Not only that, I also tried both recommendations in this stackoverflow thread about having both yarn 1x and 2x projects but it still doesn't work.

How do I get Yarn 3x plug n play to work???


Solution

  • I eventually fixed it by doing a these mess of steps that I felt I had already done before but somehow eventually worked:

    1. rm -rf ~/.yarn*
    2. yarn set version stable
    3. rm ~/package.json
    4. npx nest new [name] create new project
    5. pick yarn in CLI
    6. (yarn start:dev already works, but IDE throws error)
    7. yarn dlx @yarnpkg/sdks vscode
    8. (if you do Shift + Command + P in a TS file, then > Select Typescript Version, you have to choose Use Workspace Version, which should point to the SDK installed in step 8)

    (taken from these these threads:

    1. Can't find module yarn-3.x.x.cjs (Yarn v3)
    2. Cannot find module or its corresponding type declarations in NestJs with Yarn 3

    )

    Now I'm pretty sure step 2 is actually wrong, because you only do that in a project (i think), which created a project at my home directory, which is why I had to do rm ~/package.json. I did this after nest new told me that yarn install --silent failed, and suggested I remove package.json at my home directory. Maybe you're supposed to do corepack prepare yarn@stable --activate (from this doc)?

    But it works now, so imma leave it that way ¯\(ツ)