c# - 构建 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 install
在ClientApp
目录中执行,否则构建过程将失败缺少依赖项。
对于前端开发者来说这很正常,但是对于一些只专注于后端开发的开发者来说,这很麻烦,他们必须做一些额外的过程才能构建项目(他们通常只是ctrl + F5
和很好走)。
我尝试了以下方法:
- 将 nodejs 目录添加到
Tools -> Options -> External Web Tools
,我认为这将承认 IDE 为我完成工作,但似乎没有。 - 原始
.csproj
文件提供了这样的方法:
<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 install
ASP.NET IDE 构建过程单独使用?换句话说,我正在寻找一种在构建 ASP.NET 项目时自动安装 npm 模块的方法。
解决方案
您的配置是正确的,但这仅适用于发布您的项目将其添加到您的 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 项目之前运行
推荐阅读
- uwp - 调用 RaisePropertyChanged 时多次调用 UWP 属性集
- javascript - 按 LEVEL 遍历树
- php - WP Query 的排序结果不适用于 orderby 和 order 参数
- python-3.x - 数据缺失时用默认值填充图表
- spring - 比为 Exception.class 定义 @ExceptionHandler 来处理错误更好的方法?
- reactjs - 警告:列表中的每个孩子都应该有一个唯一的“关键”道具。反应.js
- r - 如何从附加的代码中打印单个矩阵
- python - 如何使用 PyWinAuto 单击 ListView 项?
- reactjs - 反应钩子形式 - useForm 上的钩子调用无效
- django - 在一行Django中查询中间模型