如何在gradle构建中运行自定义任务?

时间:2018-02-12 13:00:31

标签: gradle npm build.gradle npm-install

我有一个使用Gradle和NPM的Spring Boot Web应用程序。我创建了一个package.json文件,npm install工作正常。但我希望能够在运行npm install时自动运行gradle build。这是我的构建文件:

plugins {
    id 'org.springframework.boot' version '1.5.10.RELEASE'
    id 'java'
    id 'war'
    id "org.ysb33r.nodejs.base" version "0.1"
    id "org.ysb33r.nodejs.npm" version "0.1"
}
group 'com.Blahblah'
version '1.0-SNAPSHOT'


war {
    baseName = 'Blahblah'
    version =  '0.0.1'
}

sourceCompatibility = 1.8

repositories {
    mavenCentral()
    jcenter()
    maven { url "http://repo.spring.io/libs-snapshot" }
    maven { url "https://plugins.gradle.org/m2/" }
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile group: 'commons-io', name: 'commons-io', version: '2.6'
    compile group: 'commons-fileupload', name: 'commons-fileupload', version: '1.3.3'
    compile group: 'com.cloudinary', name: 'cloudinary-core', version: '1.17.0'
    compile group: 'com.cloudinary', name: 'cloudinary-http44', version: '1.17.0'
    compile group: 'mysql', name: 'mysql-connector-java', version: '6.0.6'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-data-jpa', version: '1.5.10.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-jersey', version: '1.5.10.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-mail', version: '1.5.10.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-web', version: '1.5.10.RELEASE'
    compile group: 'org.springframework.boot', name: 'spring-boot-starter-tomcat', version: '1.5.10.RELEASE'

    classpath "gradle.plugin.org.ysb33r.gradle:nodejs-gradle-plugin:0.1"

    testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test', version: '1.5.10.RELEASE'
    testCompile group: 'junit', name: 'junit', version: '4.12'
}

apply plugin: "org.ysb33r.nodejs.base"
apply plugin: "org.ysb33r.nodejs.npm"

我在ysb33rpluginsdependencies部分添加了apply plugin部分,但现在我收到错误:

classpath "gradle.plugin.org.ysb33r.gradle:nodejs-gradle-plugin:0.1"

它说:

A problem occurred evaluating root project 'Blahblah'.
> Could not find method classpath() for arguments [gradle.plugin.org.ysb33r.gradle:nodejs-gradle-plugin:0.1] on object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

在我添加ysb33r行之前,构建工作正常。可能是什么问题呢?问题解决后,我应该如何继续自动运行npm install

感谢。

1 个答案:

答案 0 :(得分:0)

有几个问题:

  1. Exec.commandLine是一个字符串数组
  2. 您的println正在配置阶段发生,将其置于doLast块中,以便在执行阶段执行
  3. 例如:

    task npmInstall(type: Exec) {
        commandLine 'npm install'.split(' ')
        doLast {
            println 'DONE!'
        }
    }
    

    不是通过npm任务调用Exec,而应该考虑gradle / nodejs插件之一。其中大多数都能够使用从存储库下载的嵌入式nodejs版本来执行nodejs命令,而不需要在机器上安装nodejs

    请参阅:https://plugins.gradle.org/search?term=nodejs

    例如:http://ysb33rorg.gitlab.io/nodejs-gradle-plugin/