Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 3.1 integration with npm

I'm working on an ASP.NET Core 3.1 application and decided to use npm to manage front end libraries, right now they should be few, but that might change in the future.

I have seen several similar questions, but they all seem to be a little outdated:

How to use NPM and install packages inside Visual Studio 2017?

How to use npm with ASP.NET Core

I intend to use npm to install the required libraries on the CI environment, I remember being able to integrate npm commands into the dotnet ones and would like to know if it is possible/recommendable.

What is the recommended approach to use npm in this newer version of ASP.NET Core?

like image 713
Luiso Avatar asked Mar 21 '20 23:03

Luiso


People also ask

How use NPM package in .NET Core?

NPM (Advanced) This will make NPM download Bootstrap, JQuery and other libraries that is used in a new asp.net core project to a folder named node_modules. Next step is to copy the files to an appropriate place. To do this we will use gulp, which also was downloaded by NPM.

Does .NET Core 3.1 require Visual Studio 2019?

The most important feature about . NET Core 3.1 is that it's a long-term support (LTS) release. If you're using Visual Studio 2019, you must update to Visual Studio 2019 version 16.4 or later to work with . NET Core 3.1 projects.

Can we use ASP.NET Core with React?

The project template creates an ASP.NET Core app and a React app. The ASP.NET Core app is intended to be used for data access, authorization, and other server-side concerns. The React app, residing in the ClientApp subdirectory, is intended to be used for all UI concerns.


1 Answers

I suggest using Yarn for two reasons:

  • For your use case, it is a drop in replacement for npm.
  • An existing Nuget package, Yarn.MSBuild, integrates Yarn into MSBuild.

Yarn.MSBuild allows you to specify Yarn commands in your .csproj. These commands run when you build your project. For example, to install front end packages on build:

  1. Add a reference to Yarn.MSBuild in your .csproj:

    <ItemGroup>
      <PackageReference Include="Yarn.MSBuild" Version="*" />
    </ItemGroup>
    
  2. Add a YarnBuildCommand property:

    <PropertyGroup>
      <YarnBuildCommand Condition="'$(Configuration)' == 'Release'">install</YarnBuildCommand>
    </PropertyGroup>
    

In the above example, yarn install runs when you build your project in release configuration. You asked specifically about building in CI using dotnet - with this setup, when you run dotnet build -c Release in CI, your front end packages are installed.

Note that by default, the command executes in your .csproj's directory. You can change this by adding a YarnWorkingDir property:

<PropertyGroup>
  <YarnWorkingDir>$(MSBuildProjectDirectory)/wwwroot/</YarnWorkingDir>
</PropertyGroup>
like image 67
JeremyTCD Avatar answered Sep 29 '22 23:09

JeremyTCD