npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@sylphx/synth-js-minify

v0.2.3

Published

JavaScript minifier using Synth's universal AST

Downloads

534

Readme

@sylphx/synth-js-minify

JavaScript minifier using Synth's universal AST - compress code while preserving functionality.

Features

  • Compact Output: Remove whitespace, minimize syntax
  • Name Mangling: Shorten variable/function names (optional)
  • Safe Compression: Preserve code semantics
  • Universal AST: Works on Synth's language-agnostic AST
  • Fast: Direct AST traversal without intermediate representations
  • Configurable: Control compression level and mangling behavior

Installation

npm install @sylphx/synth-js-minify

Usage

Basic Minification

import { minify } from '@sylphx/synth-js-minify'

const code = `
  function calculate(a, b) {
    const sum = a + b;
    const product = a * b;
    return { sum, product };
  }
`

const minified = minify(code)
console.log(minified)
// Output: function calculate(a,b){const sum=a+b;const product=a*b;return {sum:sum,product:product};}

With Options

import { minify } from '@sylphx/synth-js-minify'

const code = `
  function myLongFunctionName(param) {
    const myVariable = param * 2;
    return myVariable;
  }
`

// Enable name mangling for maximum compression
const minified = minify(code, {
  compress: true,
  mangle: true,
})
// Output: function a(b){const c=b*2;return c;}

Protect Reserved Names

import { minify } from '@sylphx/synth-js-minify'

const code = `
  function importantAPI(data) {
    return processData(data);
  }
`

const minified = minify(code, {
  mangle: true,
  reserved: ['importantAPI'], // Don't mangle this name
})
// Output: function importantAPI(a){return processData(a);}

Using the Minifier Class

import { Minifier } from '@sylphx/synth-js-minify'

const minifier = new Minifier({
  compress: true,
  mangle: false,
})

const code = 'const x = 42;'
const minified = minifier.minify(code)
console.log(minified) // "const x=42;"

// Calculate compression ratio
const ratio = minifier.compressionRatio(code)
console.log(`Reduced by ${(ratio * 100).toFixed(1)}%`)

Minify a Synth Tree Directly

import { parse } from '@sylphx/synth-js'
import { Minifier } from '@sylphx/synth-js-minify'

// Parse code to Synth AST
const tree = parse('const x = 42;')

// Minify the AST
const minifier = new Minifier()
const minified = minifier.minifyTree(tree)

console.log(minified) // "const x=42;"

Calculate Size Savings

import { minify, savings } from '@sylphx/synth-js-minify'

const original = `
  function fibonacci(n) {
    if (n <= 1) return n;
    return fibonacci(n - 1) + fibonacci(n - 2);
  }
`

const minified = minify(original)
const stats = savings(original, minified)

console.log(`Original: ${stats.originalSize} bytes`)
console.log(`Minified: ${stats.minifiedSize} bytes`)
console.log(`Saved: ${stats.savedBytes} bytes (${stats.savedPercent.toFixed(1)}%)`)

Options

interface MinifyOptions {
  /** Compress code (remove unnecessary whitespace, parentheses) */
  compress?: boolean // default: true

  /** Mangle variable names (shorten identifiers) */
  mangle?: boolean // default: false

  /** Remove comments */
  removeComments?: boolean // default: true

  /** Compact object/array literals on one line */
  compact?: boolean // default: true

  /** Preserve specific identifier names from mangling */
  reserved?: string[] // default: []
}

Examples

Different Compression Levels

import { minify } from '@sylphx/synth-js-minify'

const code = `
  function greet(name) {
    const message = "Hello, " + name + "!";
    console.log(message);
    return message;
  }
`

// Basic compression (default)
minify(code)
// function greet(name){const message="Hello, "+name+"!";console.log(message);return message;}

// With mangling (maximum compression)
minify(code, { mangle: true })
// function a(b){const c="Hello, "+b+"!";console.log(c);return c;}

Before and After

Before:

function calculateTotal(items) {
  const subtotal = items.reduce((sum, item) => sum + item.price, 0);
  const tax = subtotal * 0.08;
  const total = subtotal + tax;
  return total;
}

After (basic):

function calculateTotal(items){const subtotal=items.reduce((sum,item)=>sum+item.price,0);const tax=subtotal*0.08;const total=subtotal+tax;return total;}

After (mangled):

function a(b){const c=b.reduce((d,e)=>d+e.price,0);const f=c*0.08;const g=c+f;return g;}

API Reference

Functions

  • minify(code, options?): Minify JavaScript code string
  • savings(original, minified): Calculate compression statistics

Classes

  • Minifier: Main minifier class

    • constructor(options?): Create minifier with options
    • minify(code, options?): Minify code string
    • minifyTree(tree, options?): Minify Synth AST tree
    • compressionRatio(code, minified?): Calculate compression ratio
  • Compressor: Low-level AST-to-minified-code printer

    • constructor(options?): Create compressor with options
    • compress(tree): Convert Synth tree to minified code

Supported JavaScript Features

  • ✅ Variable declarations (var, let, const)
  • ✅ Function declarations and expressions
  • ✅ Arrow functions
  • ✅ Classes and methods
  • ✅ Object and array literals
  • ✅ Binary and unary expressions
  • ✅ If statements
  • ✅ Return statements
  • ✅ Block statements
  • ✅ Call expressions
  • ✅ Member expressions
  • ✅ Import/export statements
  • ✅ Async/await
  • ⚠️ Template literals (basic support)
  • ⚠️ For/while loops (basic support)

How It Works

  1. Parse: JavaScript code → Synth AST (via @sylphx/synth-js)
  2. Compress: Synth AST → Minified code (via Compressor)
  3. Mangle (optional): Shorten identifier names

The minifier works directly on Synth's universal AST:

  • Fast: Single-pass compression without copying
  • Safe: Preserves program semantics
  • Universal: Same AST structure for all languages

Compression Strategies

Whitespace Removal

  • Remove all unnecessary spaces, tabs, newlines
  • Keep spaces only where syntactically required (e.g., in operator)

Syntax Compaction

  • Remove optional semicolons where safe
  • Use shortest quote style for strings
  • Remove unnecessary parentheses

Name Mangling (Optional)

  • Shorten variable/function names: myVariablea
  • Preserve reserved/exported names
  • Generate collision-free short names: a, b, c, ..., z, aa, ab, ...

Performance

Typical compression ratios:

  • Basic compression: 30-50% size reduction
  • With mangling: 50-70% size reduction

The minifier is designed for speed:

  • Direct AST traversal
  • Minimal string allocations
  • No intermediate representations

Limitations

This is a foundational implementation focused on core JavaScript features:

  • Limited template literal optimization
  • Basic comment handling
  • No dead code elimination
  • No constant folding
  • Simple identifier mangling (not scope-aware)

For production use, consider tools like:

  • Terser: Full-featured JavaScript minifier
  • esbuild: Extremely fast bundler with minification
  • SWC: Fast TypeScript/JavaScript compiler

Use Cases

  • Learning: Understand how minifiers work
  • Prototyping: Quick minification in Synth-based tools
  • Integration: Minify code in Synth AST pipelines
  • Foundation: Build custom minifiers for other languages
  • Development: Reduce payload size for web applications

Comparison with Other Minifiers

This minifier is educational/foundational:

Similarities to Terser/UglifyJS:

  • Remove whitespace
  • Mangle names
  • Compact syntax

Differences:

  • Works on universal AST (can minify multiple languages)
  • Simpler implementation
  • Smaller feature set
  • Focused on correctness over maximum compression

License

MIT