首页 > 解决方案 > Gradle 无法正确执行外部命令

问题描述

我有以下 gradle 任务来使用 npm 构建前端代码:

task buildFrontend() {
    doLast {
        exec {
            workingDir "src/ui"
            commandLine "npm", "install"
            commandLine "npm", "run", "build"
        }
...
}

但是,当我运行构建时,出现以下错误:

...
> Task :solutions:dash:buildFrontend FAILED

...
> ng build --base-href /p/ --prod

sh: 1: ng: not found
npm ERR! code ELIFECYCLE
npm ERR! syscall spawn
npm ERR! file sh
npm ERR! errno ENOENT
npm ERR! dash@0.0.0 build: `ng build --base-href /p/ --prod`
npm ERR! spawn ENOENT
npm ERR! 
npm ERR! Failed at the dash@0.0.0 build script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?
...

FAILURE: Build failed with an exception.
...

* What went wrong:
Execution failed for task ':solutions:dash:buildFrontend'.
> Process 'command 'npm'' finished with non-zero exit value 1
...

但是当我cdsrc/ui目录并npm install从终端运行然后重新运行 gradle build 它将成功。commandLine "npm", "install"Gradle 的执行方式和结果似乎 与我从终端手动执行的方式不同。

但为什么?这两个命令 - gradle build 和 manualnpm install都由终端上的同一用户执行......

标签: gradlenpm

解决方案


在我将exec块分成两部分后,如下所示:

exec {
    workingDir "src/ui"
    commandLine "npm", "install"
}
exec {
    workingDir "src/ui"
    commandLine "npm", "run", "build"
}

该应用程序已构建没有错误。


推荐阅读