I have recently discovered Yarn 3 and so far I was quite happy with the PnP features. Since I mainly work with monorepos, I wanted to make use of Yarn workspaces. Unfortunately, I cannot get basic things to work. I have set up a test project to highlight the problem.
Setup & Configuration
[1] The project has the following structure
monorepo/
.env
- frontend/
- app/
- src/
- tools/
- scripts/
- src/
- script.ts
[2] I then initialise the project by running
yarn set version berry
yarn init
[3] followed by installing the basic packages to get my script running
yarn add -D typescript ts-node @types/node dotenv
yarn plugin import typescript
I have also initialised the scripts package in the scripts/ folder, running yarn init.
[4] I then added my workspaces to the freshly created package.json
// package.json
{
"name": "monorepo",
"packageManager": "[email protected]",
"devDependencies": {
"@types/node": "^17.0.22",
"dotenv": "^16.0.0",
"ts-node": "^10.7.0",
"typescript": "^4.6.2"
},
"workspaces": [
"frontend/*",
"tools/*"
],
}
[4] I run
yarn install
yarn dlx @yarnpkg/sdks vscode
to create the workspace and install the VSCode SDK to get Typescript support for my IDE.
So far so good, I can print the workspace list and everything seems to be set up right. In my script.ts file however, I want to read a constant from the .env file
// script.ts
import "dotenv/config";
const script = () => {
const getEnv = process.env.SCRIPT;
console.log(getEnv);
};
script();
and I can run
yarn ts-node tools/scripts/script.ts
>> Hello script
without problem.
The problem
Since I need the package @graphql-codegen/cli later on as a dependency I have installed this via
yarn workspace scripts add @graphql-codegen/cli
which adds a .pnp.loader.mjs to the root folder. This is not a problem as long as I don't have a tsconfig.json inside the scripts/ folder! Once I do that I get the error
Cannot find name 'process'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`.
in the script.ts file. If I add "types": ["node"] to the compiler options in the tsconfig, I get
Can't get definition file for 'node'.
I have looked at several posts but I cannot get this working. Why in the first place .pnp.loader.mjs gets installed? It seems like it's still experimental (considering the Yarn output:
ESM support for PnP uses the experimental loader API and is therefore experimental
This is driving me crazy, any suggestions? Thanks!
Alright, seems like I've solved this issue
I'm still not sure what exactly happens with
.pnp.loader.mjsand what it does exactly. I also don't know why the package@graphql-codegen/cliforces the PnP Loader to install but it seems that it somehow can't deal with workspaces. I simply had to add@types/nodeto the dependencies in thescriptspackage bythen having my
tsconfig.jsonfor thescriptspackage likeUpdate
It seems like you can also skip the
"types": ["node"]in yourtsconfig.