hexo-plugin-css-compactor
v1.0.0
Published
Minify, concat CSS files, and then insert in head tag.
Downloads
3
Readme
hexo-plugin-css-compactor
A Hexo plugin that optimizes CSS files by minifying, concatenating, and strategically placing them in your HTML output. Created from https://github.com/neoalienson/hexo-plugin-js-compactor focusing on CSS. Compatible with Hexo 5.0 or above.
Goal
This plugin aims to solve common CSS performance issues in Hexo static sites:
Problem: Static sites often load multiple small CSS files separately, causing:
- Too many HTTP requests slowing down page load
- Unoptimized CSS with unnecessary whitespace and comments
- Poor stylesheet loading order affecting page rendering
- Duplicate stylesheets loaded across different pages
- Remote dependencies may become unavailable or slow to load
Solution: Automatically optimize CSS delivery by:
- Minifying CSS files to reduce bandwidth usage
- Concatenating related stylesheets into strategic bundles
- Eliminating duplicates across your entire site
- Optimizing load order with framework styles first
- Caching remote dependencies locally for better performance
Result: Faster loading Hexo sites with fewer HTTP requests and optimized CSS delivery.
⚠️ Security Warning
IMPORTANT: When using the download feature, only download CSS files from trusted sources:
- ✅ Safe: Official CDNs (jsdelivr, cdnjs, unpkg)
- ✅ Safe: Official project repositories (GitHub releases)
- ✅ Safe: Well-known library maintainers
- ❌ Risky: Unknown or suspicious domains
- ❌ Risky: Non-HTTPS URLs (blocked by plugin)
- ❌ Risky: Files from untrusted third parties
Why this matters: Downloaded CSS files can:
- Modify your site's appearance
- Inject malicious styles
- Compromise user experience
- Load external resources
Always verify the source and integrity of remote CSS files before downloading.
How It Works
The plugin operates in three main phases during Hexo's build process:
1. Download Phase (before_generate)
- Downloads remote CSS files to local storage if configured
- Validates URLs to prevent security issues
- Caches files to avoid repeated downloads
2. Minification Phase (after_render:css)
- Minifies individual CSS files using clean-css
- Reduces file size by removing whitespace, comments, and optimizing code
- Skips files matching exclude patterns
3. Concatenation Phase (after_generate)
- Scans all HTML files for local
<link>tags - Groups stylesheets based on placement patterns:
head: Stylesheets to load in head section
- Removes duplicate stylesheet references across pages
- Combines matching stylesheets into bundle files
- Injects bundle link tags into HTML
Bundle Injection
headbundle: Injected before</head>end- Original link tags are removed to avoid duplication
Installation
npm install @neoalienson/hexo-plugin-css-compactorConfiguration
To enable the plugin add this to your _config.yml:
css_compactor:
enable: true # Enable the plugin
minify:
enable: true # Enable CSS minification
exclude: ['*.min.css'] # Skip already minified files
concat:
enable: true # Enable CSS concatenationConfiguration Options
All options are optional with sensible defaults:
- strategy: Extraction strategy (
autoormanual, default:auto)auto: Auto-discover stylesheets that appear in multiple pagesmanual: Use explicitly specified file lists
- bundle_path: Output paths for concatenated bundles (default:
/css/bundle.css) - rewrite_urls: Automatically fix relative URLs in CSS when files are moved (default:
true) - pattern: Regular expressions to match stylesheet hrefs (optional, used with
autostrategy)skip: Files to exclude from concatenationhead: Stylesheets for head section (if not specified, includes all CSS files)
- files: Explicit file lists (optional, used with
manualstrategy)head: Array of CSS files for head bundle
- debug: When enabled, logs which files are being concatenated (default:
false)
Advanced Configuration Example
css_compactor:
enable: true
minify:
enable: true
exclude: ['*.min.css']
concat:
enable: true
strategy: 'auto' # Optional: 'auto' or 'manual'
rewrite_urls: true # Optional: Fix relative URLs (default: true)
debug:
enable: false # Optional: Log concatenated files
bundle_path:
head: '/css/bundle.css' # Optional: Custom bundle path
pattern: # Optional: Regex patterns for auto strategy
skip: 'bootstrap\.min\.css'
head: '^(?!.*bootstrap\.min\.css).*$'
files: # Optional: Manual file lists (object format)
head: ['/css/main.css', '/css/theme.css']
# OR array format:
# files: ['/css/main.css', '/css/theme.css']Download Remote CSS
Download remote CSS files to local storage for better performance and offline capability:
css_compactor:
downloads:
skip_existing: true # Skip download if file already exists (default: true)
files:
- url: https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css
local: source/css/bootstrap.min.css
- url: https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css
local: source/cache/fontawesome.min.cssConfiguration Options:
skip_existing: Whentrue, skips download if local file already exists. Set tofalseto always re-download.
Security Note: Only HTTPS URLs are allowed. Files must be downloaded under the source/ folder.
URL Rewriting
When CSS files are concatenated from different directories, relative URLs (like url(../fonts/font.woff)) can break. The plugin automatically fixes these paths:
Before (in /libs/fontawesome/css/fontawesome.css):
@font-face {
src: url(../fonts/fontawesome.woff);
}After (in /css/bundle.css):
@font-face {
src: url(../libs/fontawesome/fonts/fontawesome.woff);
}Disable URL rewriting:
css_compactor:
concat:
rewrite_urls: falsePerformance Impact
- Reduced HTTP Requests: Multiple CSS files combined into 1 bundle
- Smaller File Sizes: Minification reduces bandwidth usage by 20-40%
- Better Caching: Bundled files can be cached more effectively
- Optimized Loading: Critical styles load in head section
- Fixed Asset Paths: Automatic URL rewriting maintains working font/image references
- Faster Page Speed: Typical 30-50% improvement in CSS load time
Example Workflow
Before Processing:
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/main.css">
<link rel="stylesheet" href="/css/theme.css">After Processing:
<!-- All styles bundled -->
<link rel="stylesheet" href="/css/bundle.css">Extraction Strategies
Auto Strategy (Default)
- Automatically discovers stylesheets that appear in multiple HTML files
- Only extracts commonly used stylesheets across the site
- Uses regex patterns to match and categorize stylesheets
- Good for sites with consistent stylesheet usage patterns
Manual Strategy
- Explicitly specify which CSS files to bundle
- Bundles specified files regardless of usage frequency
- Provides full control over what gets concatenated
- Ideal when you know exactly which stylesheets should be bundled
Known Issues
- Bundle files are created in both
public/andtemp/directories.
Development
Testing
Run the test suite:
npm testFile Structure
lib/
├── concat.js # Concatenation logic
├── minify.js # Minification using clean-css
└── download.js # Remote file downloadingRelated Plugins
For JavaScript optimization, consider using the companion JS compactor plugin that follows the same architecture patterns.
Contributing
Keep it simple for now. Any pull request is welcome and will be reviewed.
