我对Gradle非常陌生。昨天开始阅读相关内容,找到了一个构建Node应用的示例build.gradle文件。但是我对文件的内容有些困惑,不确定哪些是保留或预定义单词。其中一个字符串是node
,虽然未在某处使用,但我发现它是node插件所需的。
buildscript {
repositories {
mavenCentral()
maven {
url 'https://plugins.gradle.org/m2/'
}
}
dependencies {
classpath 'com.moowork.gradle:gradle-node-plugin:1.2.0'
}
}
apply plugin: 'base'
apply plugin: 'com.moowork.node' // gradle-node-plugin
node {
/* gradle-node-plugin configuration
https://github.com/srs/gradle-node-plugin/blob/master/docs/node.md
Task name pattern:
./gradlew npm_<command> Executes an NPM command.
*/
// Version of node to use.
version = '10.14.1'
// Version of npm to use.
npmVersion = '6.4.1'
// If true, it will download node using above parameters.
// If false, it will try to use globally installed node.
download = true
}
npm_run_build {
// make sure the build task is executed only when appropriate files change
inputs.files fileTree('public')
inputs.files fileTree('src')
// 'node_modules' appeared not reliable for dependency change detection (the task was rerun without changes)
// though 'package.json' and 'package-lock.json' should be enough anyway
inputs.file 'package.json'
inputs.file 'package-lock.json'
outputs.dir 'build'
}
// pack output of the build into JAR file
task packageNpmApp(type: Zip) {
dependsOn npm_run_build
baseName 'npm-app'
extension 'jar'
destinationDir file("${projectDir}/build_packageNpmApp")
from('build') {
// optional path under which output will be visible in Java classpath, e.g. static resources path
into 'static'
}
}
// declare a dedicated scope for publishing the packaged JAR
configurations {
npmResources
}
configurations.default.extendsFrom(configurations.npmResources)
// expose the artifact created by the packaging task
artifacts {
npmResources(packageNpmApp.archivePath) {
builtBy packageNpmApp
type 'jar'
}
}
assemble.dependsOn packageNpmApp
String testsExecutedMarkerName = "${projectDir}/.tests.executed"
task test(type: NpmTask) {
dependsOn assemble
// force Jest test runner to execute tests once and finish the process instead of starting watch mode
environment CI: 'true'
args = ['run', 'test']
inputs.files fileTree('src')
inputs.file 'package.json'
inputs.file 'package-lock.json'
// allows easy triggering re-tests
doLast {
new File(testsExecutedMarkerName).text = 'delete this file to force re-execution JavaScript tests'
}
outputs.file testsExecutedMarkerName
}
check.dependsOn test
clean {
delete packageNpmApp.archivePath
delete testsExecutedMarkerName
}
此外,build.gradle 如何解析?我还想知道它是如何神奇地下载 node 和 npm 工具的。
build.gradle
脚本是用 Groovy 编写的。在 Gradle 中,“node” 关键字实际上不是关键字,它是一个“任务”,并且由您在问题中引用的依赖项提供。这是一个相当复杂的示例,用于学习 Gradle,您可能需要退一步,先通过一些基本的 Gradle 教程。 - Jake Holzingernode
不是一个任务,而是一个扩展,用于定义“'com.moowork.node'”插件的整体设置。这实际上展示了新用户在Gradle中遇到的主要问题之一。它需要对Gradle功能和应用插件的概念有广泛的理解。 - Lukas Körfer