Overslaan naar hoofdinhoud

Minifier plugin 25.11

Openen in ChatGPT

De webforJ Minifier Plugin minimaliseert automatisch minifies en optimaliseert CSS- en JavaScript-assets tijdens het buildproces. De plugin ontdekt assets die worden vermeld via webforJ assetannotaties en minimaliseert deze in de buildoutput, wat de bestandsgroottes vermindert en de laadtijden verbetert zonder je oorspronkelijke bronbestanden te wijzigen.

Setup

Als je je project hebt aangemaakt met startforJ of een webforJ archetype, is de minifier-plugin al geconfigureerd en draait deze automatisch wanneer je bouwt met het prod profiel met mvn package -Pprod.

Voor handmatige setup vereist de minifier twee configuraties: een annotatieprocessor om assets tijdens de compilatie te ontdekken, en een plugin om de minificatie uit te voeren.

Voeg het volgende toe aan je pom.xml:

<build>
<plugins>
<!-- Annotatieprocessor configuratie -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<annotationProcessorPaths>
<path>
<groupId>com.webforj</groupId>
<artifactId>webforj-minify-foundation</artifactId>
<version>${webforj.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>

<!-- Minifier Plugin Configuratie -->
<plugin>
<groupId>com.webforj</groupId>
<artifactId>webforj-minify-maven-plugin</artifactId>
<version>${webforj.version}</version>
<executions>
<execution>
<goals>
<goal>minify</goal>
</goals>
</execution>
</executions>
<dependencies>
<!-- CSS-minificatie -->
<dependency>
<groupId>com.webforj</groupId>
<artifactId>webforj-minify-phcss-css</artifactId>
<version>${webforj.version}</version>
</dependency>
<!-- JavaScript-minificatie -->
<dependency>
<groupId>com.webforj</groupId>
<artifactId>webforj-minify-closure-js</artifactId>
<version>${webforj.version}</version>
</dependency>
</dependencies>
</plugin>
</plugins>
</build>

Gebruik van de plugin

Zodra de configuratie is voltooid, werkt de plugin automatisch. Gebruik eenvoudig webforJ assetannotaties in je code:

package com.example;

import com.webforj.annotation.StyleSheet;
import com.webforj.annotation.JavaScript;

@StyleSheet("ws://css/app.css")
@JavaScript("ws://js/app.js")
public class MyApp extends App {
// Je applicatiecode
}

Wanneer je je project bouwt, doet de plugin automatisch:

  1. Ontdekt assets die in annotaties tijdens de compilatie worden vermeld
  2. Minimaliseert de ontdekte CSS- en JavaScript-bestanden
  3. Rapporteert de groottevermindering en verwerkingstijd

URL-protocolresolutie

De plugin begrijpt webforJ URL-protocollen en lost deze op naar bestandsystempaden:

ProtocolLost opVoorbeeld
ws://src/main/resources/static/ws://css/app.cssstatic/css/app.css
context://src/main/resources/context://styles/app.cssstyles/app.css

URLs zonder een protocol worden niet door de minifier ondersteund en worden overgeslagen.

Ingebouwde minifiers

webforJ bevat twee productieklaar minifiers voor CSS en JavaScript.

MinifierKenmerkenSlaat over
CSSVerwijdert witruimtes, opmerkingen en optimaliseert eigenschapswaarden.min.css
JavaScriptVariabele hernoeming, dode code eliminatie, syntaxisoptimalisatie.min.js, .min.mjs

Configuratieopties

De plugin biedt opties voor het uitschakelen van minificatie, het aanpassen van JavaScript-optimalisatie en het verwerken van extra bestanden.

Uitschakelen van minificatie

Je wilt mogelijk de minificatie uitschakelen tijdens de ontwikkeling of voor foutopsporingsdoeleinden.

Via de opdrachtregel:

mvn package -Dwebforj.minify.skip=true

Via pluginconfiguratie:

<plugin>
<groupId>com.webforj</groupId>
<artifactId>webforj-minify-maven-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>

Opties voor JavaScript-minificator

De JavaScript-minificator biedt verschillende configuratieopties om het optimalisatiegedrag te beheersen.

Alleen Maven

Opties voor de JavaScript-minificator zijn momenteel alleen beschikbaar voor Maven. Gradle-ondersteuning gebruikt standaardinstellingen.

OptieStandaardBeschrijving
compilationLevelSIMPLE_OPTIMIZATIONS
  • WHITESPACE_ONLY - verwijdert alleen witruimtes en opmerkingen
  • SIMPLE_OPTIMIZATIONS - hernoeming van variabelen en verwijdering van dode code
  • ADVANCED_OPTIMIZATIONS - agressieve optimalisatie met functie-/eigendomshernoeming
languageInECMASCRIPT_NEXTInvoerversie van JavaScript: ECMASCRIPT3, ECMASCRIPT5, ECMASCRIPT_2015 tot ECMASCRIPT_2021, ECMASCRIPT_NEXT
languageOutECMASCRIPT5Uitvoerversie van JavaScript: dezelfde als languageIn, plus NO_TRANSPILE
prettyPrintfalseStel in op true om formattering voor foutopsporing te behouden

Configureer deze opties in de sectie minifierConfigurations:

<plugin>
<groupId>com.webforj</groupId>
<artifactId>webforj-minify-maven-plugin</artifactId>
<version>${webforj.version}</version>
<configuration>
<minifierConfigurations>
<closureJs>
<compilationLevel>SIMPLE_OPTIMIZATIONS</compilationLevel>
<languageIn>ECMASCRIPT_2020</languageIn>
<languageOut>ECMASCRIPT5</languageOut>
<prettyPrint>false</prettyPrint>
</closureJs>
</minifierConfigurations>
</configuration>
<executions>
<execution>
<goals>
<goal>minify</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.webforj</groupId>
<artifactId>webforj-minify-closure-js</artifactId>
<version>${webforj.version}</version>
</dependency>
</dependencies>
</plugin>

Minificeren van extra bestanden

Om bestanden te minimaliseren die niet via annotaties zijn ontdekt, maak je een configuratiebestand dat glob-patronen specificeert:

src/main/resources/META-INF/webforj-minify.txt
# Inclusiepatronen
**/*.css
**/*.js

# Uitsluitingspatronen (prefix met !)
!**/*.min.css
!**/*.min.js

Aangepaste minifiers

De plugin ondersteunt aangepaste minifiers via de Service Provider Interface (SPI) van Java, waarmee je ondersteuning kunt toevoegen voor extra bestandstypen of alternatieve minificatiebibliotheken.

Een aangepaste minifier maken

Implementeer de AssetMinifier interface om je eigen minifier te maken. Het volgende voorbeeld toont een JSON-minifier die Gson gebruikt om witruimtes te verwijderen:

src/main/java/com/example/minifier/JsonMinifier.java
package com.example.minifier;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonSyntaxException;
import com.webforj.minify.common.AssetMinifier;
import com.webforj.minify.common.MinificationException;
import java.nio.file.Path;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;

public class JsonMinifier implements AssetMinifier {

private static final Logger logger = Logger.getLogger(JsonMinifier.class.getName());
private final Gson gson = new GsonBuilder().create();

@Override
public String minify(String content, Path sourceFile) throws MinificationException {
try {
JsonElement element = gson.fromJson(content, JsonElement.class);
return gson.toJson(element);
} catch (JsonSyntaxException e) {
logger.warning("Ongeldige JSON in " + sourceFile + ", overslaan: " + e.getMessage());
return content;
} catch (Exception e) {
throw new MinificationException("Kon JSON-bestand niet minimaliseren: " + sourceFile, e);
}
}

@Override
public Set<String> getSupportedExtensions() {
return Set.of("json");
}

@Override
public boolean shouldMinify(Path filePath) {
String filename = filePath.getFileName().toString();
// Sla configuratiebestanden en al geminimaliseerde bestanden over
if (filename.equals("package.json") || filename.equals("tsconfig.json")) {
return false;
}
if (filename.endsWith("-lock.json") || filename.endsWith(".min.json")) {
return false;
}
return true;
}

@Override
public void configure(Map<String, Object> options) {
// Configuratieopties indien nodig
}
}

Je minifier registreren

Maak een configuratiebestand voor de serviceprovider:

src/main/resources/META-INF/services/com.webforj.minify.common.AssetMinifier
com.example.minifier.JsonMinifier

Gebruik je aangepaste minifier

Verpak je minifier als een aparte JAR en voeg deze toe als een plugin-afhankelijkheid:

<plugin>
<groupId>com.webforj</groupId>
<artifactId>webforj-minify-maven-plugin</artifactId>
<dependencies>
<dependency>
<groupId>com.example</groupId>
<artifactId>json-minifier</artifactId>
<version>1.0.0</version>
</dependency>
<!-- Standaard minifiers (optioneel) -->
<dependency>
<groupId>com.webforj</groupId>
<artifactId>webforj-minify-phcss-css</artifactId>
<version>${webforj.version}</version>
</dependency>
</dependencies>
</plugin>

Veelvoorkomende problemen

[WAARSCHUWING] Geen minifiers geregistreerd via SPI. Minificatie overslaan.
[WAARSCHUWING] Zorg ervoor dat ph-css en/of closure-compiler op het classpath staan.

Voeg minifier-modu afhankelijkheden toe aan de pluginconfiguratie. Voor CSS, voeg webforj-minify-phcss-css toe. Voor JavaScript, voeg webforj-minify-closure-js toe.

Als de plugin meldt 0 bestanden verwerkt, controleer dan of:

  1. De annotatieprocessor is geconfigureerd in maven-compiler-plugin met webforj-minify-foundation in annotationProcessorPaths
  2. webforJ assetannotaties aanwezig zijn in je broncode
  3. target/classes/META-INF/webforj-resources.json bestaat na compilatie
[WAARSCHUWING] Bestand niet gevonden: /pad/naar/static/css/app.css (verwezen als 'ws://css/app.css')

Controleer of het bestand op het juiste pad onder src/main/resources/static bestaat en of het URL-protocol overeenkomt met de bestandsstructuur.

[WAARSCHUWING] Fout bij het minimaliseren van bestand /pad/naar/app.css: parse-fout bij regel 42

De plugin waarschuwt maar gaat door zonder de build te laten mislukken. De originele inhoud blijft behouden wanneer de minificatie mislukt. Om syntaxisfouten te verhelpen, valideer CSS of JavaScript met een linter.