A sample .csproj file to use nextjs in ASP.Net Core projects
It is very easy to use:
1: Create a project in Visual Studio using ASP.Net Core with ReactJS template
2: Remove folder ClientApp
generated by Visual Studio
3: In project folder, run this command: npx create-next-app@latest
- Name your project whatever you want! in this example we named it
next-app
- Notice to follow the instructions on https://nextjs.org/docs/api-reference/create-next-app
4: Change the <PropertyGroup>
section in your .csproj
file to this:
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
<TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
<IsPackable>false</IsPackable>
<SpaRoot>next-app\</SpaRoot>
<DefaultItemExcludes>$(DefaultItemExcludes);$(SpaRoot)node_modules\**</DefaultItemExcludes>
<SpaProxyServerUrl>http://localhost:3000</SpaProxyServerUrl>
<SpaProxyLaunchCommand>npm run dev</SpaProxyLaunchCommand>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
5: Modify your compile itemgroup to this:
<ItemGroup>
<Compile Remove="bin\**" />
<Compile Remove="obj\**" />
<Content Remove="$(SpaRoot)**" />
<Content Remove="bin\**" />
<Content Remove="obj\**" />
<None Include="$(SpaRoot)**" Exclude="$(SpaRoot)node_modules\**" />
</ItemGroup>
6: Add this section:
<ItemGroup>
<Folder Include="next-app\" />
</ItemGroup>
7: Modify DebugEnsureNodeEnv
section to this:
<Target Name="DebugEnsureNodeEnv" BeforeTargets="Build" Condition=" '$(Configuration)' == 'Debug' And !Exists('$(SpaRoot)node_modules') ">
<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>
8: Modify/Add PublishRunWebpack
section to/following this:
<Target Name="PublishRunWebpack" AfterTargets="ComputeFilesToPublish">
<Exec WorkingDirectory="$(SpaRoot)" Command="npm install" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run build" />
<Exec WorkingDirectory="$(SpaRoot)" Command="npm run prod" />
<ItemGroup>
<DistFiles Include="$(SpaRoot)out\**" />
<ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
<RelativePath>wwwroot\%(RecursiveDir)%(FileName)%(Extension)</RelativePath>
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<ExcludeFromSingleFile>true</ExcludeFromSingleFile>
</ResolvedFileToPublish>
</ItemGroup>
</Target>
Or just copy the file in repository!!