Spring Boot: Webjars — bundle your favourite JS library easily
Probably every web application depends on some JavaScript library on CSS file. We have our own such files, but many are third party coming from other developers. Shared knowledge is nice. To include such third party library usually means to find the proper version, download it, unpack it and extract meaningful parts and put it inside out application structure. No way with web jars!
To bundle JS/CSS libraries similar way how we include java libraries into Spring Boot project, we can easily reference them inside build.gradle file (we are talking about Gradle based Spring Boot projects here, maven is quite similar). As an example we can include jQuery and Twitter Bootstrap into our project. To do so, simply open http://www.webjars.org/classic web site and find appropriate library and select version you require.
As we are running Gradle based project, we take gradle lib references and put them inside build.gradle the same way as we reference third party java libraries.
compile('org.webjars:bootstrap:3.3.7')
compile('org.webjars:jquery:2.2.1')
If we are editing Spring Boot project under IntelliJ with Gradle plugin, the project is getting updated and proper packages are downloaded and expanded. Ok, now we have both third party libraries somewhere under our project and we need to reference them in HTML. And this final part is quite easy as well. If we use Thymeleaf as a template engine, we can simply reference jQuery like this:
<script th:src="@{/webjars/jquery/2.2.1/jquery.min.js}" ></script>
Everything is very straightforward and when we decide to upgrade to latest JQuery or Twitter Bootstrap after some time, we just change appropriate version number in build.gradle file.