Когда в вашем проекте большое количество javascript-файлов, то проект начинает загружаться долго. Это связано с тем, что на каждый <script src=… браузер запускает отдельную загрузку скрипта. Чтобы ускорить открытие страницы нужно минимизировать все js-файлы и объединить их в один.
Для подключения плагина нужно добавить в свой pom.xml строки:
1 2 3 4 5 6 7 |
<pluginRepositories> <pluginRepository> <name>oss.sonatype.org</name> <id>oss.sonatype.org</id> <url>http://oss.sonatype.org/content/groups/public</url> </pluginRepository> </pluginRepositories> |
Затем выполнение плагина:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<plugin> <groupId>net.alchim31.maven</groupId> <artifactId>yuicompressor-maven-plugin</artifactId> <executions> <execution> <id>compress</id> <phase>compile</phase> <goals> <!-- Check files --> <goal>jslint</goal> <!-- Compress files --> <goal>compress</goal> </goals> </execution> </executions> <configuration> <!-- Compressed files will be put in. --> <webappDirectory>${project.build.directory}/yui-compressed</webappDirectory> <encoding>UTF-8</encoding> <!-- Force to override compressed files if they already exist. --> <force>true</force> <aggregations> <aggregation> <!-- insert new line after each concatenation (default: false) --> <insertNewLine>true</insertNewLine> <!-- Aggregated file will be in target/application.js --> <output>${project.build.directory}/application.js</output> <!-- files to include, path relative to output's directory --> <includes> <include>yui-compressed/resources/js/**/*.js</include> </includes> </aggregation> </aggregations> </configuration> </plugin> |
Эти строки настраивают выполнение плагина yuicompressor-maven-plugin на стадии компиляции. Всё описание можете посмотреть по комментариям. Смысл конфигурации в том, что этот плагин будет брать файлы из src/main/webapp (по-умолчанию), минимизаровать их и класть в target/yui-compressed. Затем будет происходить объединение всех js файлов из папки target/compressed/resources/js и всех подпапок в один файл target/application.js.
Теперь нужно настроить maven-war-plugin так, чтобы в конечном war-файле появился сгенерированный application.js и убрались все исходные файлы из resources/js:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <!-- Exclude all from resources/js --> <warSourceExcludes>resources/js/**</warSourceExcludes> <webResources> <resource> <!-- this is relative to the pom.xml directory --> <directory>${project.build.directory}/</directory> <!-- Include application.js into war. --> <includes> <include>application.js</include> </includes> <!-- application.js destination. --> <targetPath>resources/js</targetPath> </resource> </webResources> </configuration> </plugin> |
Как видно из этой конфигурации мы убираем все исходные файлы из resources/js (туда попадают файлы, которые были в src/main/webapp/resources) и добавляем туда сгенерированный файл application.js.
Полная версия pom.xml будет выглядеть так:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>ru.urvanov.examples</groupId> <artifactId>yui-compressor-example</artifactId> <packaging>war</packaging> <version>0.0.1-SNAPSHOT</version> <name>yui-compressor-example Maven Webapp</name> <url>http://maven.apache.org</url> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> </dependencies> <pluginRepositories> <pluginRepository> <name>oss.sonatype.org</name> <id>oss.sonatype.org</id> <url>http://oss.sonatype.org/content/groups/public</url> </pluginRepository> </pluginRepositories> <build> <finalName>yui-compressor-example</finalName> <plugins> <plugin> <groupId>net.alchim31.maven</groupId> <artifactId>yuicompressor-maven-plugin</artifactId> <executions> <execution> <id>compress</id> <phase>compile</phase> <goals> <!-- Check files --> <goal>jslint</goal> <!-- Compress files --> <goal>compress</goal> </goals> </execution> </executions> <configuration> <!-- Compressed files will be put in. --> <webappDirectory>${project.build.directory}/yui-compressed</webappDirectory> <encoding>UTF-8</encoding> <!-- Force to override compressed files if they already exist. --> <force>true</force> <aggregations> <aggregation> <!-- insert new line after each concatenation (default: false) --> <insertNewLine>true</insertNewLine> <!-- Aggregated file will be in target/application.js --> <output>${project.build.directory}/application.js</output> <!-- files to include, path relative to output's directory --> <includes> <include>yui-compressed/resources/js/**/*.js</include> </includes> </aggregation> </aggregations> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <configuration> <!-- Exclude all from resources/js --> <warSourceExcludes>resources/js/**</warSourceExcludes> <webResources> <resource> <!-- this is relative to the pom.xml directory --> <directory>${project.build.directory}/</directory> <!-- Include application.js into war. --> <includes> <include>application.js</include> </includes> <!-- application.js destination. --> <targetPath>resources/js</targetPath> </resource> </webResources> </configuration> </plugin> </plugins> </build> </project> |
Ссылка на тестовый проект на github:
https://github.com/urvanov-ru/java-examples/tree/master/yui-compressor-example (поставьте звезду, пожалуйста)
Скачать архив с проектом:
https://urvanov.ru/wp-content/uploads/2015/06/yui-compressor-example.zip
Полезные ссылки:
Документация на yuicompressor-maven-plugin:
http://alchim.sourceforge.net/yuicompressor-maven-plugin/index.html
Документация на maven-war-plugin:
https://maven.apache.org/plugins/maven-war-plugin/index.html
Объяснение жизненного цикла maven:
https://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html