运行 npm、ng 命令在 Windows、"The system cannot find the file specified" 错误上使用 Ant 脚本

Run npm, ng commands using Ant script on Windows, "The system cannot find the file specified" error

当我尝试 运行 以下 Ant 脚本时,该脚本执行 "npm" 命令:

<target name ="test">
    <exec executable="npm" failonerror="true">
        <arg value="install" />
    </exec>
</target>

失败并出现此错误:

Execute failed: java.io.IOException: Cannot run program "npm" 
(in directory "C:\Development\workspace\traqpath\WebSource"): 
CreateProcess error=2, The system cannot find the file specified

当我尝试 运行 Angular-CLI "ng" 命令时也会发生同样的情况:

<target name ="test">
        <exec executable="ng" failonerror="true">
            <arg value="build"/>
            <arg value="--prod"/>
            <arg value="--bh"/>
        </exec>
</target>

具有相同的错误消息,但 "ng":

Execute failed: java.io.IOException: Cannot run program "ng" 
(in directory "C:\Development\workspace\traqpath\WebSource"): 
CreateProcess error=2, The system cannot find the file specified

两个命令运行在Windows命令行中都没有问题,这说明NodeJS安装正确,并且在PATH系统变量中正确配置了NodeJS路径。

我通过修改 Ant 脚本以指定 "npm" 可执行文件的全名(以及第二种情况下的 "ng" 命令)解决了这个问题:

我的新 Ant 脚本现在看起来像这样:

<target name ="test">
    <exec executable="npm.cmd" failonerror="true">
        <arg value="install" />
    </exec>
</target>

<target name ="test">
        <exec executable="ng.cmd" failonerror="true">
            <arg value="build"/>
            <arg value="--prod"/>
            <arg value="--bh"/>
        </exec>
</target>

请注意,我使用 "npm.cmd" 而不是 "npm",并且 "ng.cmd" 而不是"ng".

<target name ="test">
        <exec executable="ng" failonerror="true">
            <arg value="build"/>
            <arg value="--prod"/>
            <arg value="--bh"/>
        </exec>
</target>

当我在 linux 中尝试 运行 时,它再次给出相同的错误,说 执行失败:java.io.IOException:无法运行程序"ng" ....

如何通过 ANT

在 linux 环境中 运行

我解决它的方法与您的解决方案类似,只是我调用了 "npm build",它默认包含在 "scripts" 部分下的 package.json 中。

<target name="build_windows">
  <exec executable="npm.cmd" failonerror="true">
    <arg value="run-script"/>
    <arg value="build"/>
  </exec>
</target>

我什至引入了另一个类似于 "build" 的 npm 脚本行,命名为 "buildprod",如下所示:

"scripts": {
  "build": "ng build -bh /context/",
  "buildprod": "ng build --prod --aot -bh /context/"
}

然后在我的 ant build.xml 文件中为生产构建引入了类似的目标,如下所示:

<target name="build_prod_windows">
  <exec executable="npm.cmd" failonerror="true">
    <arg value="run-script"/>
    <arg value="buildprod"/>
  </exec>
</target>

这样,您可以在其他 angular 项目中保留相同的 ant 脚本,而不必担心在您的 build.xml 文件中保留不同的参数。相反,您需要确保 package.json 具有正确的脚本。