Integrate Angular in Spring Boot with Gradle
Having a Angular HTML5 single page application and a Spring Boot application, we would like to serve the complete Angular app from Spring Boot. This blog shows you a couple simple steps to get everything up and running: run NPM from Gradle, integrate the Gradle front-end build in the main build and support HTML5 mode in the ResourceHandler of Spring Boot.
<!-- more -->Run NPM from Gradle
Create a subdirectory called front-end with the front-end code and build
scripts (webpack, npm). Let's assume our npm start and npm run watch output
to the /front-end/dist/ directory. First we need to make sure the front-end
code is build when we run gradle build on our project. We can use the plugin
gradle-node-plugin for this. Go
ahead and create a /front-end/build.gradle file.
Now, if we run a gradle build from our front-end subdirectory:
- node will be downloaded
npm installwill be executednpm run buildwill be executed
Run integrated Gradle build
To run the front-end submodule integrated from our root project, all we need to
do is include a settings.gradle at the root of the project.
Go ahead and run gradle build from the root of our project and see that
npm is downloaded and the expected npm tasks are run. We need to include the
distribution of the front-end build in the JAR. Thus the front-end:build task
needs to be run before we process the resources of the JAR. Go ahead and add the
following snippet to /build.gradle.
Support Angular HTML5 mode
Now all we need to do is create support for HTML5 mode in Angular. Angular is a single page application and subroutes of the application are default served with a '#' hashtag separator. If we want to have regular paths, we can enable HTML5 mode. The problem in serving this Angular HTML5 application from Spring Boot is that the Spring Boot ResourceHandler cannot find these resources, since the real resources is the index.html with the JavaScript files. With the next code snippet we instruct Spring Boot to look for the index.html as well. This is inspired by http://stackoverflow.com/questions/24837715/spring-boot-with-angularjs-html5mode
Happy coding!