TL;DR With a strong Java and Spring Framework background and looking around in the JavaScript world (Compass for the JavaScript World) it seems natural to reach out into a new technology by integrating it into a know build chain. We are going to build a Spring Boot app with Angular 4.0.0 and Gradle.
For the impatient:
The project is available on GitHub.
Note: The sample has been updated to Angular 4.3.x as described in Migrating from Angular HttpModule to new Angular 4.3 HttpClientModule.
There are lot's of Angular hello world examples out there. Most of them packed with more features than I wanted to get in touch with during my first experiments. Lucky me angular-minimum-webpack-example was created a month ago. A small example using webpack.
The first puzzle piece is gradle-node-plugin.
Gradle plugin for integrating NodeJS in your build. π
We add the plugin to our build.gradle
file...
plugins {
id "com.moowork.node" version "1.1.1"
}
and basic configuration:
node {
version = '7.9.0'
npmVersion = '4.2.0'
download = true
}
This will add some new tasks:
$ ./gradlew tasks
....
Node tasks
----------
nodeSetup - Download and install a local node/npm version.
npmInstall - Install node packages from package.json.
npmSetup - Setup a specific version of npm to be used by the build.
....
The new npmInstall
task will install all required node packages configured in package.json
into ${projectRoot}/node_modules
.
$ ./gradlew npmInstall
....
βββ @angular/common@4.0.3
βββ @angular/compiler@4.0.3
βββ @angular/core@4.0.3
βββ @angular/http@4.0.3
....
βββ¬ webpack@2.4.1
....
βββ¬ webpack-dev-server@2.4.4
....
Angular, webpack-dev-server, ... sounds interesting ...
Let's add two NodeTask
s: webpack
and serve
.
task webpack(type: NodeTask, dependsOn: 'npmInstall') {
script = project.file('node_modules/.bin/webpack')
args = ['--display-error-details']
}
task serve(type: NodeTask, dependsOn: 'webpack') {
script = project.file('node_modules/.bin/webpack-dev-server')
args = ['--content-base', 'src/main/resources/app']
}
Webpack requires quite some configuration via webpack.config.js
.
The following snippets shows the parts that need to be in sync with the configuration in the Gradle file:
const webpack = require("webpack");
var path = require('path');
module.exports = {
entry : {
'homepage': "./src/homepage.js",
},
output : {
filename : '[name].js',
path : path.resolve(__dirname, 'src/main/resources/app'),
}
}
Once everything is in place run
$ ./gradlew serve
....
:serve
Project is running at http://localhost:8080/
....
and point your browser to http://localhost:8080/.
If you grab the final project you can start the Spring Boot app with
$ ./gradlew bootRun
and see the Angular app in action at http://localhost:8080/app/index.html.
Enjoy!
PS: Our Spring Boot banner generator emerged from this template...please have a look at Create Your Own Spring Boot Banner for more details.