How to use Yarn 2 (or 3) to run create-react-app without specifying a new directory?

3.2k Views Asked by At

I am trying to migrate from NPM to Yarn for the sole reason of getting rid of 'node_modules' folder.

I am trying to use CRA tool. However, on CRA it advises to use yarn create, which is not a command found in Yarn 2 documentation. After some research I found out that I should use yarn dlx command, which is equivalent to npx.

The problem is that to use yarn dlx, I must have Yarn 2 first. Yarn 2 requires that I install it locally in my project directory. This way, I am forced to have a second layer of folder structure. I want to create-react-app in a folder on my Desktop called myApp. But, I need to create myApp folder to install Yarn 2 before I can even start using dlx to run create-react-app.

Am I missing something?

Thank you.

2

There are 2 best solutions below

0
On

Yes, for now, you have to use the second layer of the folder structure.

Assuming you have the latest version of Node 14.x, 16.x or any higher versions, the minimal instructions are the following.

Prerequisites:

  1. Ensure that corepack is enabled via corepack enable command. This needs to be done only once.

Steps:

  1. mkdir enclosing; cd enclosing - to create enclosing directory
  2. yarn set version stable - to use latest stable Yarn version in the eclosing directory and all of its subdirectories
  3. rm package.json - delete package.json in the enclosing directory, generated by the previous command to not confuse Yarn that the enclosing directory is the root of the project.
  4. yarn create react-app my-app - the project will be generated with Yarn 3 and by default will use PnP install scheme
  5. cd my-app; yarn set version latest - to attach Yarn 3+ to my-app project
  6. Optional step, if you want to use node_modules install scheme with Yarn 3+, inside my-app run yarn config set nodeLinker node-modules

After that, you can move out my-app anywhere and delete enclosing directory.

In order to simplify all this into yarn dlx create-react-app I have opened pull request to create-react-app, please place a thumb up emojo for it here: https://github.com/facebook/create-react-app/pull/12366

0
On

I faced the same situation recently... my solution was:

  1. yarn create react-app myApp (yes, is yarn 1.22 in my case)
  2. rename the package.json for a while
  3. yarn init -2 # this will create another package.json
  4. merge the old package.json with the newly created one
  5. yarn install

now you can configure PnP as is described on the Yarn documentation or...

you can create directly whit npx:
npx create-react-app your-app-name --use-pnp