如何正确打包生成源代码的 Nuget 分布式自定义工具作为构建的一部分

多亏了 Nate McMaster 的这篇精彩文章,我知道了如何将 .NET Core 控制台应用程序打包为 Nuget 包,自动将自身安装为(在本例中为预编译任务)构建任务。

为了测试是否一切正常,我只是让我的自定义工具写出一个公共 C# 类。

这是 Github 上完整且可运行的示例

但是,我的自定义工具添加的文件实际上并不是构建的一部分(第一个实际生成文件的文件),因此引入的类在第一次构建后不在程序集中(请参见 此处的第 38 行)。但是,由于 .NET Core 项目现在自动将所有 .cs 文件包含在项目旁边,因此它将新类构建到后续构建的输出中(参见此处的第 57 行)。

生成的文件不会完全消失,但通常不会像 MSBuild 任务输出的那样。但是,因为 exec 发生在目标文件中,所以我们应该可以访问所有机制来实现这一点。所以我的问题是:

我如何正确执行自定义构建工具(控制台应用程序),该工具需要检查项目及其文件并生成源代码(最好在 obj/ 中作为<foo>.g.cs单个构建的一部分编译到生成的程序集中?理想情况下,这生成的文件也不应出现在解决方案资源管理器中。

帮助!


慕婉清6462132
浏览 76回答 1
1回答

炎炎设计

在中间文件夹中生成中间文件(CustomTool.g.cs)时(您需要对其进行解析,请参阅 Refit 库中的示例:https ://github.com/reactiveui/refit/blob/5b4e14aaf8a1fcc27396b7c08171d100aba1b97d/Refit/targets&nbsp;/refit.targets#L11&nbsp;);&nbsp;您需要将其显式添加为编译项。以您的示例目标文件(https://github.com/aniongithub/CustomTool/blob/master/CustomTool/RunCustomTool.targets#L13)为例:<Project>&nbsp; <PropertyGroup>&nbsp; &nbsp; <IntermediateOutputPath Condition="$(IntermediateOutputPath) == '' Or $(IntermediateOutputPath) == '*Undefined*'">$(MSBuildProjectDirectory)obj\$(Configuration)\</IntermediateOutputPath>&nbsp; &nbsp; <!-- Command to invoke CustomTool -->&nbsp; &nbsp; <CustomTool>dotnet "$(MSBuildThisFileDirectory)/netcoreapp2.2/CustomTool.dll"</CustomTool>&nbsp; &nbsp; <!-- Other variables&nbsp; -->&nbsp; &nbsp; <CustomVariable>"$(MSBuildProjectDir)"</CustomVariable>&nbsp; </PropertyGroup>&nbsp; <Target Name="CustomTool" BeforeTargets="CoreCompile" DependsOnTargets="PrepareForBuild">&nbsp; &nbsp; <Exec Command="$(CustomTool) $(ProjectPath) $(IntermediateOutputPath)CustomTool.g.cs" />&nbsp; &nbsp; <!-- add generated file as a compile item, otherwise it won't get picked up -->&nbsp; &nbsp; <ItemGroup Condition="Exists('$(IntermediateOutputPath)\CustomTool.g.cs')">&nbsp; &nbsp; &nbsp; <Compile Include="$(IntermediateOutputPath)\CustomTool.g.cs" />&nbsp; &nbsp; </ItemGroup>&nbsp; </Target></Project>
打开App,查看更多内容
随时随地看视频慕课网APP