首页 > 解决方案 > 构建 ASP.NET Core 项目时如何自动安装 npm 模块

问题描述

我正在构建一个以 ASP.NET Core Web API 作为后端,以 React SPA 作为前端的项目,文件夹结构如下所示:

WebApiProject
│
├── ClientApp/
│   ├── public/
│   ├── src/
│   └── package.json
│
├── Controller/
├── Models/
├── appsettings.json
├── Program.cs
└── Startup.cs

当我将新的 npm 模块添加到 React 项目(这将更新 package.json)并推送到我们的团队 Git 存储库时,其他团队成员必须在拉取新提交后手动npm installClientApp目录中执行,否则构建过程将失败缺少依赖项。

对于前端开发者来说这很正常,但是对于一些只专注于后端开发的开发者来说,这很麻烦,他们必须做一些额外的过程才能构建项目(他们通常只是ctrl + F5和很好走)。


我尝试了以下方法:


<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\**; $(SpaRoot)build-ssr\**" />
    <ResolvedFileToPublish Include="@(DistFiles->'%(FullPath)')" Exclude="@(ResolvedFileToPublish)">
      <RelativePath>%(DistFiles.Identity)</RelativePath>
      <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
    </ResolvedFileToPublish>
  </ItemGroup>
</Target>

在发布时,它似乎是 ASP.NET 项目的某种自动脚本,但我不太清楚如何调整它,以便它在开发模式构建时完成工作。


有没有办法让npm installASP.NET IDE 构建过程单独使用?换句话说,我正在寻找一种在构建 ASP.NET 项目时自动安装 npm 模块的方法。

标签: c#reactjsvisual-studioasp.net-corenpm

解决方案


您的配置是正确的,但这仅适用于发布您的项目将其添加到您的 csproj 文件

 <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>

这将确保您的项目npm install在您启动 ASP.Net Core 项目之前运行


推荐阅读