Build Spring boot with gradle and webpack

When you want to run spring boot microservices with a web user interface which is bundled with webpack, you may want to integrate the webpack into gradle.

Usually microservices is running without web user interface, it exposes its API to other service or client directly. Which means, you should develop the microservices and web user interface in separated projects.

But there is always exception in real practice. If you just want to put your webpack bundle in the spring boot application, and run spring boot application with the web user interface, you can follow the guide below.

Screen Shot 2019-08-07 at 5.46.34 PM

First, create your web content resources in your spring boot project

Usually, you can access spring boot static web content under /src/main/resources/static, or /src/main/resources/public folder, you should place your html, css or image files here.

Please notice that the admin.template.html is the webpack entry page, you could use the default index.html. Place package.json and webpack.config.js as needed into the project root path. There is no special settings for these two files.

Then add the following lines in build.gradle file

bootJar {
    ...
    sourceSets {
		main {
			resources {
				exclude 'static/admin**'
			}
		}
	}
    ...
}

task webpack(type: Exec) {
     commandLine "$projectDir/node_modules/.bin/webpack"
}

processResources.dependsOn 'webpack'

The task webpack is to tell gradle how to execute webpack command.
On the other side,
webpack creates a bundle js file as well as uses the entry page template in your project (here is admin.template.html which you can define it in webpack.config.js), it will copy the template file to the build patch and add the bundle js reference to the html.

As gradle copies the resource to build path, it will override any file each time when run the build. To avoid gradle build overwrite webpeck entry page, you need to exclude the target entry page from the source path.

Now you can just run the following command to build web user interface as well as spring boot application at a time

gradle bootRun 

In addition, if you want to watch the build update for development, just run watcher with webpack command

webpack --watch

Then after you run spring boot, you could keep updating the bundle js file for development purpose.

Author: chooli.yip

I love to explorer the wild nature with huge curiosity

Leave a comment