codebase-asset-optimizer
TypeScript icon, indicating that this package has built-in type declarations

1.1.3 • Public • Published

Codebase Asset Optimizer

Professional CLI tool for optimizing and managing assets in codebases. Never increase file sizes again!

License: MIT Private Repository

🎯 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

# 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
# ✅ 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)

npx codebase-asset-optimizer setup

Option 2: Automatic (during fresh install)

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:

{
  "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:

# 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

# 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

# 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.

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).

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.

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.

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:

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:

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:

brew install ffmpeg

Ubuntu/Debian:

sudo apt-get install ffmpeg

Windows: Download from 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:

# 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:

# 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

🆘 Support


Made with ❤️ for developers who care about performance

Package Sidebar

Install

npm i codebase-asset-optimizer

Weekly Downloads

3

Version

1.1.3

License

MIT

Unpacked Size

198 kB

Total Files

36

Last publish

Collaborators

  • vladgrecuaris