【问题标题】:Can I do a loop in an MSBuild file?我可以在 MSBuild 文件中执行循环吗?
【发布时间】:2012-10-18 06:00:06
【问题描述】:

目前,我在MSBuild proj 文件中找到了他的以下代码。这真的很简单。定义 4 个 变量 并为每个变量调用一次我的 MSBuild 任务:

请代码~~

<ItemGroup><JS_File1 Include="file1.js"/></ItemGroup>
<ItemGroup><JS_File1 Include="file2.js"/></ItemGroup>
<ItemGroup><JS_File1 Include="file3.js"/></ItemGroup>
<ItemGroup><JS_File1 Include="file4.js"/></ItemGroup>

<JavaScriptCompressorTask SourceFiles="@(JS_File1)" OutputFile="@(JS_File1).min"/>
<JavaScriptCompressorTask SourceFiles="@(JS_File2)" OutputFile="@(JS_File2).min"/>
<JavaScriptCompressorTask SourceFiles="@(JS_File3)" OutputFile="@(JS_File3).min"/>
<JavaScriptCompressorTask SourceFiles="@(JS_File4)" OutputFile="@(JS_File4).min"/>

没有什么令人兴奋的。

我想知道这是否可以重构为这样的东西。

失败伪代码~~

<ItemGroup>
    <JS_File1 Include="file1.js"/>
    <JS_File1 Include="file2.js"/>
    <JS_File1 Include="file3.js"/>
    <JS_File1 Include="file4.js"/>
</ItemGroup>

<!-- now this is the shiz i have no idea about -->
foreach(@(JS_Files))
    <JavaScriptCompressorTask SourceFiles="@(theFile)" OutputFile="@(theFile).min"/>

在 MSBuild 中是否可以这样做?

所以该任务被称为“每个文件一次”.. 还是更确切地说,“项目组中的每个项目一次”?

【问题讨论】:

    标签: loops msbuild refactoring iteration


    【解决方案1】:

    您可以使用项目元数据来批处理任务(请参阅http://msdn.microsoft.com/en-us/library/ms171474.aspx)。

    所有项目都有名为“身份”的元数据,其中包含 Include 属性的值。如果您使用元数据引用语法%(Identity),这将指示 MSBuild 为每个唯一的 Include 值执行您的任务。

    <ItemGroup>
        <JS_File1 Include="file1.js"/>
        <JS_File1 Include="file2.js"/>
        <JS_File1 Include="file3.js"/>
        <JS_File1 Include="file4.js"/>
    </ItemGroup>
    
    <JavaScriptCompressorTask SourceFiles="@(JS_File1)" OutputFile="%(Identity).min"/>
    

    请注意,MSBuild 知道您正在引用 JS_File1 项组的身份元数据,因为您在任务中引用了它。否则,您将需要使用语法%(JS_File1.Identity)

    【讨论】:

      【解决方案2】:

      像这样,除了使用你的任务而不是我的副本......

      <?xml version="1.0" encoding="utf-8"?>
      <Project ToolsVersion="4.0" DefaultTargets="Minifier" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
      
        <Target Name="Minifier">
          <ItemGroup>
            <JS_File1 Include="file1.js"/>
            <JS_File1 Include="file2.js"/>
            <JS_File1 Include="file3.js"/>
            <JS_File1 Include="file4.js"/>
          </ItemGroup>
      
          <Copy SourceFiles="@(JS_File1)" DestinationFiles="@(JS_File1->'%(Filename).min')"/>
      
        </Target>
      </Project>
      

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2021-02-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-09
        • 2020-07-22
        • 2016-12-25
        相关资源
        最近更新 更多