@playform/compress

repository·Current·Indexed 20 days ago

https://github.com/playform/compress

An Astro integration that provides a suite of compression utilities to optimize statically generated builds and pre-rendered routes. It supports CSS (via csso and lightningcss), HTML (via html-minifier-terser), JavaScript (via terser), Images (via sharp), SVG (via svgo), and JSON. The integration allows for custom path mapping, file exclusions, and configuration overrides for the underlying optimization engines.

Tokens
2.3K
Snippets
8
Records
12
Agent score
71%

What's inside @playform/compress

  1. Overview of Compress capabilities

    Current

    The Compress Astro integration provides several compression utilities for your statically generated builds and pre-rendered routes.

    Supported formats:

    • CSS: via csso and lightningcss
    • HTML: via html-minifier-terser
    • Image: via sharp
    • JavaScript: via terser
    • SVG: via svgo
    • JSON
    IMPORTANT

    Use Compress last in your integration list to ensure it can optimize the output of other integrations.

    Note: Compress does not compress network requests; it only optimizes your static build files and pre-rendered routes.

  2. Understand why `astro` is a dependency instead of a peerDependency

    Current

    In @playform/compress and @playform/pipe, astro is intentionally listed in dependencies with a wildcard version ("astro": "*") rather than in peerDependencies.

    This approach is used to avoid several common issues encountered with Astro integrations:

    1. Avoids Version Pinning: Using a wildcard (*) ensures the integration does not force a specific version of Astro, preventing mismatches in transitive dependencies (like @astrojs/internal-helpers) that can break builds during Astro major version upgrades.
    2. Eliminates Installation Friction: By avoiding peerDependencies, the package avoids triggering peer dependency resolution checks that often require users to use the legacy-peer-deps flag in npm.
    3. Ensures Type Availability: Keeping astro in dependencies ensures that TypeScript can resolve Astro's type definitions when the integration imports from astro.
    4. Enables Deduplication: Package managers like npm and yarn will see the "*" wildcard and reuse the version of astro already present in the host project, preventing duplicate installations.
  3. Install the Compress Astro integration

    Current

    You can install the @playform/compress integration using the Astro CLI or by manual installation.

    Run the following command in your project directory and follow the prompts to automatically install dependencies and update your astro.config.* file:

    npx astro add @playform/compress

    (Or use yarn astro add @playform/compress or pnpx astro add @playform/compress depending on your package manager.)

    Manual Installation

    1. Install the package as a development dependency:
      npm install -D -E @playform/compress
    2. Add the integration to your astro.config.* file:
      export default {
        integrations: [(await import("@playform/compress")).default()],
      };
    npx astro add @playform/compress
  4. Configure default compression options

    Current

    The @playform/compress integration automatically compresses CSS, HTML, SVG, JavaScript, JSON, and image files in the Astro outDir. You can override the default settings for each file type by passing configuration objects directly to the underlying engines:

    • CSS: Uses csso or lightningcss.
    • HTML: Uses html-minifier-terser.
    • Images: Uses sharp (supports avci, avcs, avif, avifs, gif, heic, heics, heif, heifs, jfif, jif, jpe, jpeg, jpg, apng, png, raw, tiff, webp).
    • SVG: Uses svgo.
    • JavaScript: Uses terser.

    To disable a specific type of compression, set its key to false in the configuration object.

    export default {
    	integrations: [
    		(await import("@playform/compress")).default({
    			CSS: false,
    			HTML: {
    				"html-minifier-terser": {
    					removeAttributeQuotes: false,
    				},
    			},
    			Image: false,
    			JavaScript: false,
    			JSON: false,
    			SVG: false,
    		}),
    	],
    };
  5. Exclude files from compression

    Current

    Use the Exclude option to prevent specific files from being compressed. The Exclude property accepts an array containing:

    • Strings: Exact file name matches.
    • Regular Expressions: Pattern-based matches.
    • Functions: Custom logic that takes a File: string argument and returns a boolean.
    export default {
    	integrations: [
    		(await import("@playform/compress")).default({
    			Exclude: [
    				"File.png",
    				(File: string) =>
    					File === "./Target/Favicon/Image/safari-pinned-tab.svg",
    			],
    		}),
    	],
    };
  6. Control logging verbosity

    Current

    Adjust the level of detail in the console output using the Logger parameter.

    • The default value is 2.
    • Set Logger: 0 to disable debug messages and reduce log noise.
    export default {
    	integrations: [
    		(await import("@playform/compress")).default({
    			Logger: 0,
    		}),
    	],
    };
  7. Configure compression paths and input-output mapping

    Current

    By default, the utility compresses the Astro outDir. You can customize which directories are processed using the Path option.

    Single or Multiple Paths

    Pass a string or an array of strings to specify one or more directories to compress.

    Input-Output Mapping

    To compress files from one directory into a different target directory, use a Map or an array containing a Map. This allows you to define specific source-to-destination relationships.

    You can mix standard paths and maps within a single Path array.

    // Multiple paths
    Path: ["./dist", "./Compress"]
    
    // Input-Output Mapping using a Map
    Path: new Map([["./Source", "./Target"]])
    
    // Mixed: Compress one directory, and map another to a different target
    Path: [
    	"./Target",
    	new Map([["./Target", "./TargetCompress"]]),
    ]
  8. Supported file types and optimization engines

    Current

    The @playform/compress plugin supports the following file types, each utilizing specific underlying tools:

    TypeEngine(s) Used
    CSSlightningcss or csso
    HTMLhtml-minifier-terser
    JavaScriptterser
    Imagesharp
    SVGsvgo
    JSONNative JSON.parse/stringify (for whitespace removal)

    For Images, the plugin uses sharp. It automatically detects if an image is animated (like webp or gif) to set appropriate flags.

  9. Fix Astro transitive dependency errors using `overrides`

    Current

    If you encounter a build error where a requested module from @astrojs/internal-helpers is missing an export (e.g., collapseDuplicateLeadingSlashes), it is likely due to a version mismatch caused by a pinned dependency in an integration.

    You can resolve this by adding an overrides block to your project's package.json to force the correct version of the internal helper.

    {
    	"overrides": {
    		"@astrojs/internal-helpers": "0.8.0"
    	}
    }
  10. Use the Compress CLI interface

    Current

    The Interface provides a programmatic way to invoke the compression process. It accepts an array of file patterns to compress and an optional pattern for the output directory or destination. The function returns a Promise<void> that resolves when the compression task is complete.

    // The interface signature:
    // (File: Pattern[], Compress?: Pattern): Promise<void>;
  11. Configure @playform/compress via the default export

    Current

    The default export is a function used to initialize the @playform/compress plugin, typically within an Astro configuration. It accepts an options object to define compression behavior for various file types.

    Key configuration properties include:

    • Path: A string, Set, Array, or Map defining the directories to process.
    • Map: An object mapping file types to glob patterns (e.g., { CSS: 'src/**/*.css' }).
    • Exclude: Patterns to exclude from compression.
    • CSS, HTML, Image, JavaScript, SVG, JSON: Configuration objects for specific minifiers/optimizers.
    • Cache: Configuration for caching, specifically Search which can be set to the constant J to use the build directory.
    • Logger: Configuration for logging behavior.
    import compress from "@playform/compress";
    
    // Example usage in an Astro config context
    const config = compress({
      Path: "dist",
      Map: {
        CSS: "**/*.css",
        JavaScript: "**/*.js"
      },
      CSS: {
        lightningcss: true
      },
      JavaScript: {
        terser: { compress: true }
      }
    });
  12. Reference: @playform/compress exported symbols

    Current

    The following symbols are exported from the integration entrypoint:

    • Default: The default configuration object used when options are not provided.
    • Merge: A utility function for merging configuration objects.
    • Search: A constant used to indicate that the cache search should target the build directory.
    • System: The system-relative path context.
    • _Action: The internal action object used during the compression lifecycle.
    • default: The main plugin function used for integration.