Search code examples
reactjsasp.net-coreyarnpkg

Make VS2019 use Yarn instead of NPM


When I start running my ASP.Net Core/React webapp, it uses NPM to download the packages. I'd like it to use Yarn instead.

I can use Yarn from the command line and it restores the packages fine. I've also installed this extension which works great, using Yarn to restore packages, but only when I make a change to package.json.

What I need is a way to use Yarn when I checkout the code for the first time and hit the green 'Run' button in Visual studio, where it tries to run it, realises node_modules is missing, and then tries to download the packages.

I thought it might be a case of adding this kind of thing to my scripts section in package.json

"start": "yarn react-scripts start",
"build": "yarn react-scripts build",

But so far it always uses NPM.

Background: in the course of upgrading some packages to fix some other issues, NPM made a right mess, whereas Yarn does it properly.

Thanks


Solution

  • The answer lies in the CSPROJ file. I am not familiar with yarn to properly swap it out with npm, but this is how VS is able to build and publish dotnet + react/angular/vue projects.

    If you do a file -> new ReactJs application you can dissect the CSPROJ fairly easily.

    For example; Here VS is hooking into the BeforeTargets="Build", so when the project is built, it can execute npm install.

    <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
        ...
        <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
    </Target>