codebase-asset-optimizer
Version:
Professional CLI development tool for optimizing and managing assets in codebases. Detects unused assets, optimizes images to WebP, optimizes videos, and automatically replaces asset references. GIFs are preserved unchanged to maintain animation functiona
449 lines (327 loc) โข 12.8 kB
Markdown
# Codebase Asset Optimizer
> Professional CLI tool for optimizing and managing assets in codebases. Never increase file sizes again!
[](https://opensource.org/licenses/MIT)
[](https://github.com/vladgrecu/codebase-asset-optimizer)
## ๐ฏ Features
- **Smart Size Detection**: Only optimizes assets if it reduces file size
- **Unused Asset Detection**: Find and safely remove unused images/videos
- **Automatic Reference Updates**: Updates all code references when optimizing assets
- **Multiple Optimization Strategies**: WebP for images, efficient codecs for videos
- **Backup & Restore**: Safe operations with automatic backup creation
- **Cross-Platform**: Works on Windows, macOS, and Linux
- **CLI & Programmatic API**: Use as a command-line tool or integrate into your build process
## ๐ Quick Start
### Installation
```bash
# Install as dev dependency (recommended)
npm install --save-dev codebase-asset-optimizer
# Or install globally for system-wide usage
npm install -g codebase-asset-optimizer
# Or clone the private repository (access required)
git clone https://github.com/vladgrecu/codebase-asset-optimizer.git
cd codebase-asset-optimizer
npm install && npm run build
```
### Why Dev Dependency?
This tool is designed to be a **development dependency** because:
- ๐ง **Build-time optimization**: Runs during development and build processes, not at runtime
- ๐ฆ **Smaller production bundles**: Keeps your production `node_modules` lean
- ๐ **CI/CD integration**: Perfect for build pipelines and automated optimization
- ๐ก **Development workflow**: Used for asset analysis and optimization during development
```bash
# โ
Recommended - Install as dev dependency
npm install --save-dev codebase-asset-optimizer
# โ Not recommended - Runtime dependency
npm install codebase-asset-optimizer
```
### Setup npm Scripts
After installation, you can add convenient npm scripts to your `package.json` in several ways:
#### Option 1: Interactive Setup (Recommended)
```bash
npx codebase-asset-optimizer setup
```
#### Option 2: Automatic (during fresh install)
```bash
npm install --save-dev codebase-asset-optimizer
# ๐ Thank you for installing Codebase Asset Optimizer!
# ๐ฆ Found package.json: package.json
# ๐ก For future projects, install as dev dependency:
# npm install --save-dev codebase-asset-optimizer
# ๐ Would you like to add convenient npm scripts to your package.json?
# npm run optimize:assets # Optimize all assets
# npm run optimize:assets:dry # Preview optimizations (safe)
# npm run audit:assets # Analyze optimization opportunities
# npm run clean:assets # Remove unused assets
# npm run assets:interactive # Interactive optimization mode
```
#### Option 3: Manual Setup
If automatic setup doesn't work, manually add these scripts to your `package.json`:
```json
{
"scripts": {
"optimize:assets": "npx codebase-asset-optimizer optimize",
"optimize:assets:dry": "npx codebase-asset-optimizer optimize --dry-run",
"audit:assets": "npx codebase-asset-optimizer audit",
"clean:assets": "npx codebase-asset-optimizer clean",
"assets:interactive": "npx codebase-asset-optimizer interactive"
}
}
```
After setup, you can use convenient npm scripts:
```bash
# Quick start - see what can be optimized
npm run audit:assets
# Preview optimizations (safe, no changes made)
npm run optimize:assets:dry
# Optimize all assets (only if size reduction achieved)
npm run optimize:assets
# Interactive mode with guided steps
npm run assets:interactive
```
### Manual Usage
```bash
# Use directly with npx (primary command)
npx codebase-asset-optimizer audit
npx codebase-asset-optimizer optimize
npx codebase-asset-optimizer clean
# Alternative short commands (for convenience)
npx asset-optimizer audit
npx optimize-assets
# Or if installed globally
codebase-asset-optimizer --help
```
### Basic Usage
```bash
# Audit your project for optimization opportunities
codebase-asset-optimizer audit
# Preview what would be optimized (dry run)
codebase-asset-optimizer optimize --dry-run
# Optimize all assets (only if size reduction is achieved)
codebase-asset-optimizer optimize
# Remove unused assets
codebase-asset-optimizer clean
# Interactive mode with guided options
codebase-asset-optimizer interactive
```
## ๐ What It Does
### Asset Optimization
- **Images**: Converts to WebP format with smart quality settings
- **Videos**: Re-encodes to WebM/MP4 with optimal compression
- **GIF Preservation**: GIF files are intentionally left unchanged to preserve animations
- **Size Verification**: Only keeps optimized versions if they're actually smaller
- **Reference Updates**: Automatically updates all imports/references in your codebase
### Unused Asset Detection
- **Smart Scanning**: Searches through all source files for asset references
- **Pattern Matching**: Finds direct imports, dynamic references, and path-based usage
- **Safe Removal**: Creates backups before removing any files
### Professional Features
- **Backup System**: Automatic backup creation with restore capabilities
- **Progress Reporting**: Real-time feedback with detailed statistics
- **Error Handling**: Robust error handling with helpful messages
- **Dry Run Mode**: Preview changes before applying them
- **npm Integration**: Automatic setup of convenient npm scripts during installation
- **Interactive Mode**: User-friendly guided optimization process
## ๐ ๏ธ CLI Commands
### `audit`
Analyze your project to find unused and optimizable assets.
```bash
codebase-asset-optimizer audit [options]
Options:
-d, --dir <directory> Project directory (default: current)
-p, --public <directory> Public/assets directory
-s, --source <directory> Source code directory
-v, --verbose Verbose output
```
### `optimize`
Optimize assets to efficient formats (only if size reduction is achieved).
```bash
codebase-asset-optimizer optimize [options]
Options:
-d, --dir <directory> Project directory (default: current)
-p, --public <directory> Public/assets directory
-s, --source <directory> Source code directory
--no-backup Skip creating backup
-y, --yes Skip confirmation prompts
--dry-run Show what would be optimized
-v, --verbose Verbose output
```
### `clean`
Remove unused assets safely.
```bash
codebase-asset-optimizer clean [options]
Options:
-d, --dir <directory> Project directory (default: current)
-p, --public <directory> Public/assets directory
-s, --source <directory> Source code directory
--no-backup Skip creating backup
-y, --yes Skip confirmation prompts
--dry-run Show what would be removed
-v, --verbose Verbose output
```
### `interactive`
Launch interactive mode with guided options.
```bash
codebase-asset-optimizer interactive [options]
Options:
-d, --dir <directory> Project directory (default: current)
-p, --public <directory> Public/assets directory
-s, --source <directory> Source code directory
```
## ๐ Programmatic API
Use the optimizer programmatically in your build scripts:
```typescript
import { AssetOptimizer, createDefaultConfig } from "codebase-asset-optimizer";
async function optimizeAssets() {
// Create configuration
const config = createDefaultConfig("/path/to/project");
// Create optimizer instance
const optimizer = new AssetOptimizer(config);
// Run audit
const results = await optimizer.audit();
console.log(`Found ${results.optimizableAssets.length} optimizable assets`);
// Optimize assets (with backup)
const stats = await optimizer.optimizeAssets(true);
console.log(
`Optimized ${stats.optimized} assets, saved ${stats.sizeBefore - stats.sizeAfter} bytes`
);
// Remove unused assets
if (results.unusedAssets.length > 0) {
const cleanupResults = await optimizer.removeUnusedAssets(true);
console.log(`Removed ${cleanupResults.removed} unused assets`);
}
}
optimizeAssets().catch(console.error);
```
## โ๏ธ Configuration
The tool automatically detects your project structure, but you can customize it:
```typescript
import { createDefaultConfig } from "codebase-asset-optimizer";
const config = createDefaultConfig("/path/to/project");
// Customize settings
config.optimization.images.quality = 90;
config.optimization.images.maxWidth = 1920;
config.optimization.videos.targetFormats = ["webm"];
config.largeFileThreshold = 1024 * 1024; // 1MB
// Image optimization settings
config.optimization.images = {
targetFormat: "webp",
quality: 85,
maxWidth: 2048,
maxHeight: 2048,
onlyIfSmaller: true, // Critical: only optimize if it reduces size
};
// Video optimization settings
config.optimization.videos = {
targetFormats: ["webm", "mp4"],
quality: "medium",
maxWidth: 1920,
maxHeight: 1080,
onlyIfSmaller: true, // Critical: only optimize if it reduces size
};
```
## ๐ง Requirements
- **Node.js**: 16.0.0 or higher
- **Sharp**: Automatically installed for image optimization
- **FFmpeg**: Required for video optimization (auto-detected or install manually)
### Installing FFmpeg
**macOS:**
```bash
brew install ffmpeg
```
**Ubuntu/Debian:**
```bash
sudo apt-get install ffmpeg
```
**Windows:**
Download from [https://ffmpeg.org/download.html](https://ffmpeg.org/download.html)
## ๐ Example Output
```
๐ Starting Asset Audit
๐ Discovering assets...
Found 156 image/video assets (22.1 MB)
๐ Checking asset usage...
Processed 156/156 assets
๐ฏ Identifying optimization opportunities...
Found 134 assets that can be optimized
๐ Generating report...
๐ ASSET AUDIT RESULTS
==================================================
Total Assets: 156 (22.1 MB)
๐ BY TYPE:
Images: 149 total (145 used, 4 unused)
Videos: 7 total (7 used, 0 unused)
๐พ USAGE:
Used: 152 (21.98 MB)
Unused: 4 (117.05 KB)
๐ฏ OPTIMIZATION:
Optimizable: 134 (20.85 MB)
- Images โ WebP: 134
- Videos โ efficient: 0
๐ Starting optimization...
๐ Optimizing: playground-banner.png
โ 1.54 MB โ 39.83 KB (97% smaller)
๐ Optimizing: hero-image.jpg
โ 856 KB โ 312 KB (64% smaller)
...
โ
Optimization complete!
Assets processed: 134
Successfully optimized: 127
Total savings: 8.2 MB (39% reduction)
Duration: 23.4s
```
## ๐งช Testing & Development
### Test Project
A comprehensive test project is included for validation and development:
```bash
# Navigate to test project
cd test-project
# Run interactive optimization
npm run test:optimizer
# Reset to original state after testing
npm run reset
# View asset statistics
npm run stats
```
The test project includes:
- **67 assets** (65 images + 2 videos)
- **8 source files** with various reference patterns
- **Multiple frameworks** (HTML, CSS, React, Vue, Markdown)
- **Reset functionality** to restore original state
### Reset Functionality
After testing optimizations, easily reset the test project:
```bash
# Automatic reset (uses backup or git)
npm run reset
# Manual backup creation
npm run backup:create
# Check restoration status
npm run stats
```
The reset script automatically:
- Restores assets from the most recent backup
- Reverts all source code references to original extensions
- Cleans up optimization artifacts and reports
- Verifies complete restoration
## ๐๏ธ Project Structure Support
The tool automatically detects common project structures:
- **Public directories**: `public`, `assets`, `static`, `dist/public`
- **Source directories**: `src`, `app`, `lib`, `source`
- **File types**: Images (PNG, JPG, WebP, SVG), Videos (MP4, WebM, MOV)
## ๐ก๏ธ Safety Features
- **Backup Creation**: Automatic backups before any destructive operations
- **Size Verification**: Never increases file sizes through optimization
- **Dry Run Mode**: Preview changes before applying them
- **Error Recovery**: Detailed error messages and graceful failure handling
- **Reference Integrity**: Automatically updates all code references
## ๐ค Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
## ๐ License
MIT ยฉ [Vlad Grecu](https://github.com/vladgrecu)
## ๐ Support
- ๐ [Documentation](https://github.com/vladgrecu/codebase-asset-optimizer#readme)
- ๐ [Issue Tracker](https://github.com/vladgrecu/codebase-asset-optimizer/issues)
- ๐ฌ [Discussions](https://github.com/vladgrecu/codebase-asset-optimizer/discussions)
<p align="center">
<strong>Made with โค๏ธ for developers who care about performance</strong>
</p>