node.js - 在 gradle-node-plugin 中配置 nodeModulesDir

标签 node.js gradle gradle-plugin

我正在尝试设置 npm 包的缓存。这是我的插件配置:

node {
  version = '4.5.0'
  npmVersion = '3.10.6'
  distBaseUrl = 'https://nodejs.org/dist'
  download = true

  workDir = file("$webAppSourceAbsolute/nodejs")

  nodeModulesDir = file("$webAppSourceAbsolute/")
}

这是我的任务:

task npmCacheConfig(type: NpmTask) {
  description = "Configure the NPM cache"
  outputs.upToDateWhen {
    false
  }
  def npmCacheDir = "${gradle.getGradleUserHomeDir()}/caches/npm"
  outputs.files file(npmCacheDir)
  args = ['config', 'set', 'cache', npmCacheDir]
}

但是当我运行这个任务时,我得到了一个错误:

:arm-bpa:nodeSetup UP-TO-DATE
:arm-bpa:npmCacheConfig FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':myModule:npmCacheConfig'.
> 
  Could not run npm command - local npm not found but requested in gradle node configuration.
  A common reason for this is an npm-shrinkwrap.json file is present and un-installs npm.
  To resolve this, add npm with version '3.10.6' to your package.json.

我可以这样解决:

npmCacheConfig.doFirst {
  this.project.node.nodeModulesDir = file("$webAppSourceAbsolute/nodejs/node-v4.5.0-linux-x64/lib/")
}

npmCacheConfig.doLast {
  this.project.node.nodeModulesDir = file("$webAppSourceAbsolute/")
}

没有这种硬编码,有什么方法可以修复它吗?

最佳答案

我是这样修复的:

npmCacheConfig.doFirst {
    def nodeJsDirectory = null
    def nodeVersion = this.project.node.version

    file("$webAppSourceAbsolute/nodejs/").traverse(
            type: FileType.DIRECTORIES,
            nameFilter: ~"^node-v$nodeVersion.*",
            postDir: {
                return FileVisitResult.TERMINATE
            }
    ) {
        nodeJsDirectory = it
    }

    if (nodeJsDirectory != null) {
        this.project.node.nodeModulesDir = file("$nodeJsDirectory/lib/")
    } else {
        throw new IllegalStateException("nodejs is not installed")
    }
}


npmCacheConfig.doLast {
    this.project.node.nodeModulesDir = file("$webAppSourceAbsolute/")
}

关于node.js - 在 gradle-node-plugin 中配置 nodeModulesDir,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39080747/

相关文章:

java - Java Gradle API 的 Maven 依赖参数是什么?

javascript - 如何设置与主文件分开的快速路线?

javascript - react.js : how to load local react. js 而不是使用在线的

node.js - Azure Functions + Azure SQL + Node.js 和请求之间的连接池?

android - 发行版本变体因 “androidx.fragment:fragment-testing”库的debugImplementation失败

android - 如何解决 java.util.zip.ZipException?

node.js - 如何从头开始创建使用 API 进行身份验证的 SAML IDP

gradle - 如何将Jacoco插件与Gradle集成?

android - 如何在 Android Studio 2.3.2 上解析 'unable to find valid certification path to requested target'

java - Gradle 在自定义任务中设置属性