Skip to main content

oxc-minify

A high-performance JavaScript minifier for Node.js. Reduce code size through compression, mangling, and tree-shaking with Terser-compatible options.

Installation

npm install oxc-minify
pnpm add oxc-minify
yarn add oxc-minify

Quick Start

import { minifySync } from 'oxc-minify';

const result = minifySync(
  'app.js',
  'function add(a, b) { return a + b; } console.log(add(1, 2));'
);

console.log(result.code);
// Output: function add(n,o){return n+o}console.log(add(1,2));

API Functions

minifySync

Synchronous minification on the current thread. This is the recommended function for most use cases.
function minifySync(
  filename: string,
  sourceText: string,
  options?: MinifyOptions
): MinifyResult
filename
string
required
The name of the file being minified. Used for error messages and source maps.
sourceText
string
required
The JavaScript source code to minify.
options
MinifyOptions
Configuration options for minification. See MinifyOptions for details.
Returns: MinifyResult

Example

import { minifySync } from 'oxc-minify';

const code = `
  function calculateTotal(items) {
    return items.reduce((sum, item) => sum + item.price, 0);
  }
  export { calculateTotal };
`;

const result = minifySync('utils.js', code, {
  compress: true,
  mangle: true,
  sourcemap: true
});

console.log(result.code);
console.log(result.map);

minify

Asynchronous minification on a separate thread.
This function can be slower than minifySync due to thread spawning overhead. Use minifySync unless you have a specific need for async.
function minify(
  filename: string,
  sourceText: string,
  options?: MinifyOptions
): Promise<MinifyResult>
filename
string
required
The name of the file being minified.
sourceText
string
required
The source code to minify.
options
MinifyOptions
Configuration options for minification.
Returns: Promise<MinifyResult>

MinifyOptions

Configuration options for minification behavior.

Basic Options

module
boolean
default:"false"
Treat the code as an ES module. Enables more aggressive top-level optimizations.
const result = minifySync('module.js', code, {
  module: true  // Enables top-level mangling for modules
});
sourcemap
boolean
default:"false"
Generate source maps for the minified code.
const result = minifySync('app.js', code, {
  sourcemap: true
});

console.log(result.map); // Source map object

Compression Options

compress
boolean | CompressOptions
default:"true"
Enable or configure code compression. When true, uses default compression settings.
// Enable with defaults
{ compress: true }

// Disable compression
{ compress: false }

// Custom compression settings
{
  compress: {
    dropConsole: true,
    dropDebugger: true,
    unused: true
  }
}
CompressOptions interface:

Mangling Options

mangle
boolean | MangleOptions
default:"true"
Enable or configure variable name mangling. When true, uses default mangling settings.
// Enable with defaults
{ mangle: true }

// Disable mangling
{ mangle: false }

// Custom mangling settings
{
  mangle: {
    toplevel: true,
    keepNames: false
  }
}
MangleOptions interface:

Code Generation Options

codegen
boolean | CodegenOptions
default:"true"
Configure code generation and whitespace removal.
{
  codegen: {
    removeWhitespace: true  // default
  }
}

// Keep formatting (disable minification)
{
  compress: false,
  mangle: false,
  codegen: {
    removeWhitespace: false
  }
}

Tree Shaking

Advanced tree-shaking options for removing dead code.
interface TreeShakeOptions {
  // Respect pure annotations (@__PURE__, #__NO_SIDE_EFFECTS__)
  annotations?: boolean;  // default: true
  
  // Manually mark functions as pure
  manualPureFunctions?: string[];
  
  // Whether property reads have side effects
  propertyReadSideEffects?: boolean | 'always';  // default: 'always'
  
  // Whether accessing globals has side effects
  unknownGlobalSideEffects?: boolean;  // default: true
  
  // Whether invalid imports have side effects
  invalidImportSideEffects?: boolean;  // default: true
}

Pure Annotations

const code = `
  /* @__PURE__ */ console.log('debug');
  productionCode();
`;

const result = minifySync('app.js', code, {
  compress: {
    treeshake: {
      annotations: true  // Respect @__PURE__ comments
    }
  }
});
// Output: productionCode();

Manual Pure Functions

const code = `
  debug('message');
  logAnalytics('event');
  runApp();
`;

const result = minifySync('app.js', code, {
  compress: {
    treeshake: {
      manualPureFunctions: ['debug', 'logAnalytics']
    }
  }
});
// Output: runApp();

Property Side Effects

const code = `
  const x = obj.prop;  // May trigger getter
  foo();
`;

const result = minifySync('app.js', code, {
  compress: {
    treeshake: {
      // false: Assume property reads have no side effects
      // true: Assume they might have side effects
      // 'always': Always assume side effects (safest)
      propertyReadSideEffects: false
    }
  }
});

MinifyResult

The result of minification, containing the minified code, source maps, and any errors.
code
string
The minified JavaScript code. Empty string if parsing failed.
const { code } = minifySync('app.js', sourceCode);
console.log(code);
map
SourceMap | undefined
Source map for the minified code. Only present if sourcemap: true.
interface SourceMap {
  version: number;
  sources: string[];
  sourcesContent?: string[];
  names: string[];
  mappings: string;
  file?: string;
  sourceRoot?: string;
}
errors
OxcError[]
Parse and minification errors.
if (result.errors.length > 0) {
  console.error('Minification errors:');
  result.errors.forEach(error => {
    console.error(error.message);
  });
}

Common Use Cases

Production Build

import { minifySync } from 'oxc-minify';
import { readFileSync, writeFileSync } from 'fs';

const source = readFileSync('src/app.js', 'utf-8');

const result = minifySync('app.js', source, {
  module: true,
  compress: {
    dropConsole: true,
    dropDebugger: true,
    unused: true
  },
  mangle: {
    toplevel: true
  },
  sourcemap: true
});

if (result.errors.length > 0) {
  console.error('Minification failed:', result.errors);
  process.exit(1);
}

writeFileSync('dist/app.min.js', result.code);
writeFileSync('dist/app.min.js.map', JSON.stringify(result.map));

console.log(`Minified: ${source.length}${result.code.length} bytes`);

Development Build (Readable Output)

const result = minifySync('app.js', code, {
  compress: false,
  mangle: false,
  codegen: {
    removeWhitespace: false  // Keep formatting
  }
});

// Output is formatted and readable
console.log(result.code);

Remove Debug Code

const code = `
  function main() {
    if (DEBUG) {
      console.log('Debug info');
      debugger;
    }
    return production();
  }
`;

const result = minifySync('app.js', code, {
  compress: {
    dropConsole: true,
    dropDebugger: true
  },
  define: {
    DEBUG: 'false'
  }
});

// Debug code is completely removed

Library Bundle

const libraryCode = `
  export function publicAPI() {
    return helper();
  }
  
  function helper() {
    return 'implementation';
  }
`;

const result = minifySync('lib.js', libraryCode, {
  module: true,
  compress: true,
  mangle: {
    toplevel: false,  // Don't mangle exports
    keepNames: {
      function: true  // Preserve function names
    }
  }
});

Maximum Compression

const result = minifySync('app.js', code, {
  module: true,
  compress: {
    dropConsole: true,
    dropDebugger: true,
    unused: true,
    joinVars: true,
    sequences: true,
    treeshake: {
      annotations: true,
      propertyReadSideEffects: false
    }
  },
  mangle: {
    toplevel: true,
    keepNames: false
  }
});

// Smallest possible output

Target Specific ES Version

const modernCode = `
  const obj = { ...spread };
  const value = optional?.chaining ?? fallback;
  try { risky(); } catch { /* no binding */ }
`;

const result = minifySync('app.js', modernCode, {
  compress: {
    target: 'es2015'  // Transform and minify to ES2015
  }
});

Error Handling

import { minifySync, type OxcError } from 'oxc-minify';

function minifyWithErrorHandling(filename: string, code: string) {
  const result = minifySync(filename, code, {
    compress: true,
    mangle: true
  });

  if (result.errors.length > 0) {
    console.error(`Minification errors in ${filename}:`);
    
    result.errors.forEach((error: OxcError) => {
      console.error(`  [${error.severity}] ${error.message}`);
      
      if (error.labels && error.labels.length > 0) {
        error.labels.forEach(label => {
          console.error(`    at position ${label.start}-${label.end}`);
          if (label.message) {
            console.error(`    ${label.message}`);
          }
        });
      }
      
      if (error.helpMessage) {
        console.log(`  Hint: ${error.helpMessage}`);
      }
      
      if (error.codeframe) {
        console.error('\n' + error.codeframe);
      }
    });
    
    // Decide whether to fail or use partial result
    if (result.code === '') {
      throw new Error('Minification completely failed');
    }
    
    console.warn('Using partially minified output despite errors');
  }

  return result;
}

Comparing Before and After

import { minifySync } from 'oxc-minify';

function analyzeMinification(filename: string, code: string) {
  const result = minifySync(filename, code, {
    compress: true,
    mangle: true
  });

  const originalSize = Buffer.byteLength(code, 'utf-8');
  const minifiedSize = Buffer.byteLength(result.code, 'utf-8');
  const savings = originalSize - minifiedSize;
  const percent = ((savings / originalSize) * 100).toFixed(2);

  console.log('Minification Results:');
  console.log(`  Original:  ${originalSize.toLocaleString()} bytes`);
  console.log(`  Minified:  ${minifiedSize.toLocaleString()} bytes`);
  console.log(`  Savings:   ${savings.toLocaleString()} bytes (${percent}%)`);

  return result;
}

analyzeMinification('bundle.js', largeBundle);

Performance Tips

Use minifySync

The synchronous API is faster as it avoids thread spawning overhead.

Profile Your Settings

Test different options to find the best balance between size and speed for your use case.
// Faster, slightly larger
{ compress: { sequences: false } }

// Slower, smaller
{ compress: { sequences: true } }

Cache Minified Output

Minification is deterministic. Cache results based on source content hash.

Parallelize Large Projects

Use worker threads to minify multiple files in parallel.
import { Worker } from 'worker_threads';

// In worker: minifySync(filename, code)

Source Maps for Debugging

Enable source maps in production for better error tracking.
const result = minifySync(filename, code, {
  sourcemap: process.env.NODE_ENV === 'production'
});

Integration Examples

Build Script

import { minifySync } from 'oxc-minify';
import { glob } from 'glob';
import { readFile, writeFile, mkdir } from 'fs/promises';
import { join, dirname } from 'path';

async function buildProject() {
  const files = await glob('src/**/*.js');
  
  for (const file of files) {
    const source = await readFile(file, 'utf-8');
    
    const result = minifySync(file, source, {
      module: true,
      compress: { dropConsole: true },
      mangle: true,
      sourcemap: true
    });
    
    if (result.errors.length > 0) {
      console.error(`Errors in ${file}:`, result.errors);
      continue;
    }
    
    const outFile = file.replace('src/', 'dist/');
    await mkdir(dirname(outFile), { recursive: true });
    await writeFile(outFile, result.code);
    await writeFile(`${outFile}.map`, JSON.stringify(result.map));
    
    console.log(`✓ ${file}${outFile}`);
  }
}

buildProject();

Bundler Plugin

import { minifySync } from 'oxc-minify';

export function oxcMinifyPlugin(options = {}) {
  return {
    name: 'oxc-minify',
    
    renderChunk(code, chunk) {
      if (process.env.NODE_ENV !== 'production') {
        return null;
      }
      
      const result = minifySync(chunk.fileName, code, {
        module: true,
        ...options
      });
      
      if (result.errors.length > 0) {
        this.error(`Minification failed: ${result.errors[0].message}`);
      }
      
      return {
        code: result.code,
        map: result.map
      };
    }
  };
}

Type Definitions

Full TypeScript definitions are included:
import type {
  MinifyOptions,
  MinifyResult,
  CompressOptions,
  MangleOptions,
  CodegenOptions,
  TreeShakeOptions,
  SourceMap,
  OxcError
} from 'oxc-minify';

Parser API

Parse JavaScript/TypeScript into an AST

Transform API

Transform JavaScript/TypeScript code

Minifier Tool

Learn more about the Oxc minifier

Node.js Integration

Integrate Oxc into your Node.js workflow

Build docs developers (and LLMs) love