使用ant执行npm

3

我希望自动化构建一个包含前端和后端的应用程序。为此,我想使用 Maven 和 Ant 进行平台无关的复制和 CLI 任务。对于一些 CLI 如 docker ...,这是可行的。但对于由 npm 提供的 CLI 或 npm 本身则不行。

<exec executable="docker">
    <arg line="version"/>
</exec>
<!--Works-->
<exec executable="C:\Program Files\nodejs\npm.cmd">
    <arg line="version"/>
</exec>
<!--Doesn't work-->
<exec executable="npm">
    <arg line="version"/>
</exec>

如第二个例子所示,如果我指定npm.cmd的完整路径,脚本就可以工作。但这应该至少在windows和unix上工作。因此,指定完整路径不是一个选择。
有没有办法从ant运行npm及其模块?
晚些编辑:
真正的问题是,windows节点安装程序也将名为npm的文件放置在bin文件夹中,这是一个针对cygwin的bash脚本。npm bin文件夹已添加到全局PATH环境变量中,Windows cmd会选择正确的二进制文件,因为它使用PATHEXT环境变量来确定什么可执行,什么不可执行。ant exec插件不使用PATHEXT,只执行命名为npm的第一个文件,这将导致失败。解决方案是将路径中的纯npm文件重命名。这样,ant首先看到npm.cmd文件,一切都顺利进行。

1
对于 npm,您应该寻找支持 npm 等的 frontend-maven-plugin - khmarbaise
这解决了我的问题。如果您写一个答案,我会很乐意接受它。 - Ohmen
4个回答

11

我知道这已经过时了,但这是我所拥有的,并且为未来的其他人提供帮助。适用于我们的 macOS、Unix 和 Windows 系统。

  <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" />
    <attribute name="dir" description="Directory to execute task" />
    <element name="args" implicit="yes" description="Argument to pass to the exec task" />
    <sequential>
      <exec executable="cmd.exe" dir="@{dir}" failonerror="@{failonerror}" osfamily="winnt">
        <arg line="/c  @{module}" />
        <args />
      </exec>
      <exec executable="@{module}" dir="@{dir}" failonerror="@{failonerror}" osfamily="unix" logError="true">
        <args />
      </exec>
    </sequential>
  </macrodef>

那么像这样的事情可以奏效

    <exec-node dir="${node.project.dir}" module="npm" failonerror="true" >
      <arg value="run" />
      <arg value="lint" />
    </exec-node>

当然,您可以像npm一样硬编码模块,或者将其设置为默认值,但我使用npm和npx。


2
据我所知,通过antrun插件直接调用npm是不可能的。但我成功地通过在Windows上使用/c参数调用cmd来运行它。
例如:
<exec executable="cmd">
    <arg line="/c npm run babel -- src/main/webapp/js/es6/ --presets babel-preset-es2015 --out-dir src/main/webapp/js/"/>
</exec>

在Mac上怎么样? - Artanis Zeratul
这是一个相当老的答案,现在我建议不要使用它,而是使用exec-maven-plugin来调用在您的package.json中定义的脚本。 - ATNPGO
抱歉,目前这个项目只有使用Ant作为选项。 - Artanis Zeratul

1

这对我在Windows上有效:

<exec executable="npm.cmd">
    <arg value="version"/>
</exec>

谢谢,但这个解决方案必须在Unix和Windows上运行,所以引用 npm.cmd 不是一个解决方案。我已经将使用的解决方案添加到问题中。 - Ohmen
你可以像 @jaime-garza 的回答中所述添加一个 osfamily。 - teleclimber

-1

抱歉,但我认为这里的上下文是Ant而不是Maven。 - Artanis Zeratul
那你就不应该打上“maven”标签。我已经修复了。 - khmarbaise

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接