17

有没有将 grunt 与 ant 集成的好教程?我们当前的构建使用 ant,因为我们是一家 Java 商店。然而,前端开始成为一等公民,我们正在研究使用 node 和 grunt 进行前端构建。我需要将前端构建与 ant 构建集成。我需要知道如何规范化所有自定义任务以及内置 grunt 任务的退出代码,并在 ant 调用 grunt 任务时将控制台输出限制为这些预定义代码。任何帮助将不胜感激。

4

3 回答 3

15

你可以使用这个宏:

<macrodef name="exec-node">
    <attribute name="module" description="The name of the NodeJS module to execute"/>
    <attribute name="failonerror" default="true" description="Fail if the exit code is not 0"/>
    <element name="args" implicit="yes" description="Argument to pass to the exec task"/>
    <sequential>
        <exec executable="cmd.exe" failonerror="@{failonerror}" osfamily="winnt">
            <arg line="/c  @{module}" />
            <args/>

            <!-- Windows cmd output workaround: http://stackoverflow.com/a/10359327/227349 -->
            <!-- Forces node's stderror and stdout to a temporary file -->
            <arg line=" &gt; _tempfile.out 2&lt;&amp;1"/>

            <!-- If command exits with an error, then output the temporary file        -->
            <!-- to stdout delete the temporary file and finally exit with error level 1  -->
            <!-- so that the apply task can catch the error if @failonerror="true"        -->
            <arg line=" || (type _tempfile.out &amp; del _tempfile.out &amp; exit /b 1)"/>

            <!-- Otherwise, just type the temporary file and delete it-->
            <arg line=" &amp; type _tempfile.out &amp; del _tempfile.out &amp;"/>
        </exec>
        <exec executable="@{module}" failonerror="@{failonerror}" osfamily="unix">
            <args/>
        </exec>
    </sequential>
</macrodef>

您可以调用任何命令:例如:

<target name="jshint">
    <exec-node module="grunt">
        <arg value="jshint" />
    </exec-node>
</target>

像魅力一样工作:还确保 stderr 也被打印,这是调用 grunt 时的常见问题。

于 2013-06-26T14:31:02.890 回答
2

Grunt 可以调用命令行,因此您可以轻松地在 grunt 中创建几个任务,这些任务除了通过 shell 执行 ant 任务之外什么都不做。

grunt-shell库使得从 grunt 任务执行外部命令变得特别容易:https ://github.com/sindresorhus/grunt-shell

但是,由于您在谈论自定义退出代码,因此您可能最终必须编写自己的自定义 grunt 任务,该任务执行 shell 命令,然后查看响应代码(可能使用grunt.helpers.spawn帮助程序):https://github .com/gruntjs/grunt/blob/master/docs/api_utils.md#gruntutilsspawn

我的建议?我的组织最近经历了同样的事情,如果可能的话,最好与 ant 彻底断绝关系,并为您的 JavaScript 相关项目完全摆脱它。

Grunt 有一个不断增长和有用的插件库,如果你不能复制你的 ant 构建文件并创建一个 100% 的 javascript 解决方案,我会感到惊讶。

于 2012-10-02T23:37:16.653 回答
0

您可以使用http://abc.tools.qafoo.com/,其中包含一个 npm 模块 *1)

然后,您唯一需要的是一个自定义目标,例如:

…

<target
    name="-mm:compile:main~hooked"
   extensionOf="-compile:main~hook"
    depends="
        -my-compile-npm-hook
    " 
>

<target
    name="-my-compile-npm-hook"
>
    <echo>install local grunt-cli</echo>
    <antcall target="npm:install">
        <param name="in.npm.package.name" value="grunt-cli" />
    </antcall>
</target>

…

之后,您可能会在.npm/node_modules/.bin/目录别名中运行 grunt ${npm.local.modulesdir}/.bin/ ^^ 不要错过包含或定义来自的属性src/main/resources/extensions/npm/npm.properties

*1):不幸的是,当前的 node.js 版本有问题

于 2013-05-22T19:42:01.123 回答