How to tell gradle to install npm within the project on build?
Solution 1
As @Oliver Charlesworth said, Gradle has his limitations, but you can create a custom gradle task.
Example:
task npmInstall(type: Exec) {
workingDir 'src/main/webapp'
commandLine 'npm', 'install'
}
Add the build dependency to your war
build step
war {
dependsOn npmBuild
}
Solution 2
As Tim Hovius says: you can create your own task.
If you don't want it to execute all the time, you can add the OnlyIf clause.
(From the official documentation: https://docs.gradle.org/current/dsl/org.gradle.api.Task.html#org.gradle.api.Task:onlyIf(groovy.lang.Closure)
myTask.onlyIf(new Spec<Task>() {
boolean isSatisfiedBy(Task task) {
return isProductionEnvironment();
}
});
OR
You can write the task more intelligently using standard Groovy. For example:
task doSomething {
doLast {
def file = new File("dummy.txt")
if (file.exists()) {
project.exec {
commandLine 'someCommand', 'parameter'
}
}
}
}
OR
In your build.gradle for example
task doSomething {
doLast {
...
}
}
doSomething.enabled = (some condition goes here)
Related videos on Youtube
Comments
-
Milo almost 2 years
My angular 4 UI for a java web application depends only on the below few bundles. I ran the below commands from webapps root. App works fine. I want to know the best practices as I'm new to angular.
npm install rxjs npm install @angular/[email protected] @angular/[email protected] @angular/[email protected] @angular/[email protected] @angular/[email protected] @angular/[email protected] @angular/[email protected] --save npm install [email protected] --save npm install [email protected] --save
I'm referring the installed bundles from
systemjs.config.js
like below:paths: { 'npm:' : 'node_modules/' }, map: { '@angular/core' : 'npm:@angular/core/bundles/core.umd.js' . . }
Queries:
- The app should not be heavy, could not include the entire
node_modules
inwar
- If I keep
node_modules
in project root instead of webapps, how do I refer it fromsystemjs.config.js
- I just want those bundles and not the huge file stack that gets downloaded while running
npm install @angular/cli
- If we can use global
node_modules
, how to refer to that fromsystemjs.config.js
(I prefer keeping it within project not to disturb other applications in the server using different versions) - Finally, what should I include in
build.gradle
to download the required bundles while gradle builds
-
Oliver Charlesworth over 6 yearsGradle doesn't have native understanding of the JS ecosystem. You can try e.g. the gradle-node-plugin, but it's a bit limited, in my experience.
- The app should not be heavy, could not include the entire
-
Oliver Charlesworth over 6 yearsThe issue with this is it's going to run
npm install
every time. So ideally you want to find some way to denote when the task is up to date. -
Tim Hovius over 6 yearsYou are right, but the dependencies will be downloaded once, so only the first time the task consumes some time.