Until now all I had to generate form Maven was either a JAR file, or a WAR for web apps or EAR for enterprise applications. But this week I got a new task: I had to export the frontend (HTML, CSS, JS and all other assets, like images, etc) of the web application I am working on in a zip archive. I could have done this from /bin/bash, as I am already running some command line statements to run webpack and compile my React JS project, but I already output two EAR files based on the same frontend during Maven build, so I thought it would be more elegant to generate the 3rd output from Maven as well, despite it being a simple zip archive.
In order to generate a zip archive in Maven, I used the maven-assembly-plugin
. To use it, simply add it to the build/plugins
element:
<project>
....
<build>
<plugins>
...
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<descriptor>src/assembly/bin.xml</descriptor>
<finalName>my-application</finalName>
</configuration>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Two important parameters must be set: finalName
will be the name of the archive generated, in my case it will be my-application.zip/my-application.tar/… and descriptor
is the location of the descriptor file used by the plugin. This is a simple XML file where we specify the type of the archive (zip/tar/tar.gz/tar.bz2) and which files we’d like to include.
My descriptor file is located at src/assembly/bin.xml
and looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<formats>
<format>zip</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>src/main/webapp</directory>
<outputDirectory>web-app</outputDirectory>
<includes>
<include>**/*</include>
</includes>
</fileSet>
</fileSets>
</assembly>
As you can see, I have specified that I want the archive to be a zip. You may specify a while bunch of other formats as well, if you specify multiple formats, the Maven plugin will create multiple archives, one for each format specified. In my case I want the whole src/main/webapp
folder added to the zip archive with all files in it and in its sub-folders. You may specify multiple fileSet elements to create multiple folders in the archive and you may also filter the included files. Here you may find more info on the maven-assembly-plugin
.
After running a Maven build, the resulting file in my case would look like this:
my-application.zip
└─ web-app
└─ css
└─ style.css
└─ images
└─ flags
└─ de.png
└─ hu.png
└─ uk.png
└─ logo.png
└─ js
└─ bundle.min.js
└─ index.html