Creating a (.NET 6 based) website project with ASP.NET Core and React (TypeScript) in Visual Studio 2022?

SFM61319 1 Reputation point
2022-03-04T18:15:48.08+00:00

I have been trying to set up an ASP.NET Core + React (TypeScript) web app project in Visual Studio 2022, but couldn't succeed in doing so. There are no proper stacks/suites(?) in the Visual Studio 2022 create project dialog (File > New > Project...) that suit my needs.

I then tried what [these docs](https://learn.microsoft.com/en-us/visualstudio/javascript/tutorial-asp-net-core-with-react?view=vs-2022 "Create an ASP.NET Core app with React") say - and it works - but when I do the same for React TypeScript (i.e., using Standalone TypeScript React Template instead of Standalone JavaScript React Template) it doesn't work because this template doesn't have an Add integration for Empty ASP.NET Web API project. option in its setup (but the JavaScript template does).

How do I create an ASP.NET Core + React (TypeScript) project then?

I did see some modified and new files when the ASP.NET Core Web API integration option was enabled during the React.js (not TypeScript) setup. Can I copy those ASP.NET Core Web API integration files and their content, re-write the JavaScript files in TypeScript, and add those files (*.ts instead of *.js, etc.) in the TypeScript template? Or is there any other (official) method to properly set up an ASP.NET Core + React (TypeScript) project in Visual Studio 2022?

Do note the docs say:

The standalone TypeScript React Template is not currently supported in this tutorial.

...which is why I'm looking for alternative (but proper and if possible "official") working methods to set up the project.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,165 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Bruce (SqlWork.com) 56,021 Reputation points
    2022-03-04T22:09:40.743+00:00

    the standard

    dotnet new react

    creates a standard react project in ClientApp. to add typescript support follow the react official instructions, in the ClientApp folder:

    npm install --save typescript @types/node @types/react @types/react-dom @types/jest

    you can now rename files to .tsx and update code to typescript

    note: as you convert to typescript you may be missing typedefs. see each package on how to install. also I'd update to the current react scripts in the project file, as the template is rather old. the react-router is old syntax also.

    you can also just create a new react app with any tool, and replace ClientApp files.

    rm -rf ClientApp  
    npx create-react-app clientapp --template typescript  
    mv clientapp ClientApp  
    

    the folder rename is required because create-react-app does not support uppercase.

    4 people found this answer helpful.

  2. Bruce (SqlWork.com) 56,021 Reputation points
    2022-03-05T20:02:28.017+00:00

    you can use the default react template, and edit. you can put any npm SPA application in the ClientApp folder.

    the SPA support is all in the project file. the addition of the spa proxy package for dev, configuration for the proxy (only used in dev), and the build and deploy tasks for a npm based spa package.

    you can change the ClientApp folder to any name you like.

    <Project Sdk="Microsoft.NET.Sdk.Web">  
      
      <PropertyGroup>  
        <TargetFramework>net6.0</TargetFramework>  
        <Nullable>enable</Nullable>  
        <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>  
        <TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>  
        <IsPackable>false</IsPackable>  
        <SpaRoot>ClientApp\</SpaRoot>  
        <DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>  
        <SpaProxyServerUrl>https://localhost:44455</SpaProxyServerUrl>  
        <SpaProxyLaunchCommand>npm start</SpaProxyLaunchCommand>  
        <ImplicitUsings>enable</ImplicitUsings>  
      </PropertyGroup>  
      
      <ItemGroup>  
        <PackageReference Include="Microsoft.AspNetCore.SpaProxy" Version="6.0.2" />  
      </ItemGroup>  
      
      <ItemGroup>  
        <!-- Don't publish the SPA source files, but do show them in the project files list -->  
        <Content Remove="$(SpaRoot)**" />  
        <None Remove="$(SpaRoot)**" />  
        <None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />  
      </ItemGroup>  
      
      <Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">  
        <!-- Ensure Node.js is installed -->  
        <Exec Command="node --version" ContinueOnError="true">  
          <Output TaskParameter="ExitCode" PropertyName="ErrorCode" />  
        </Exec>  
        <Error Condition="'$(ErrorCode)' != '0'" Text="Node.js is required to build and run this project. To continue, please install Node.js from https://nodejs.org/, and then restart your command prompt or IDE." />  
        <Message Importance="high" Text="Restoring dependencies using 'npm'. This may take several minutes..." />  
        <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />  
      </Target>  
      
      <Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">  
        <!-- As part of publishing, ensure the JS resources are freshly built in production mode -->  
        <Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />  
        <Exec WorkingDirectory="$(SpaRoot)" Command="npm run build" />  
      
        <!-- Include the newly-built files in the publish output -->  
        <ItemGroup>  
          <DistFiles Include="$(SpaRoot)build\**" />  
          <ResolvedFileToPublish Include="@(DistFiles-&gt;'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">  
            <RelativePath>wwwroot\%(RecursiveDir)%(FileName)%(Extension)</RelativePath>  
            <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>  
            <ExcludeFromSingleFile>true</ExcludeFromSingleFile>  
          </ResolvedFileToPublish>  
        </ItemGroup>  
      </Target>  
    </Project>  
    

    like I said, the easiest approach is to create a dotnet react app. delete the ClientApp folder and create a new one with create-react-app or your favorite tool.

    note: create-react-app doesn't like uppercase in the folder/app name, so you should use "clientapp" (or any other name you like) and update the project file (on Mac/Os and linux and the folder names are case sensitive).

    the dotnet react template is rather old anyway. it uses class components instead of function components with hooks, and the old react-router syntax. Even though you plan on using typescript, you should still create function components.

    here is a typescript cheatsheet:

    https://react-typescript-cheatsheet.netlify.app/docs/basic/setup

    note: typescript compile is blocked because you are typically using web pack for the build.

    1 person found this answer helpful.