Universal text and code minification utility for Node.js and browser environments.
Supports:
- JavaScript / TypeScript (via Terser)
- JSON / JSONC
- HTML / XML
- CSS
- YAML / SQL / Shell
- Plain text fallback
- Single API for all file types
- Automatic syntax detection by filename
- Terser-powered JS/TS minification
- Safe fallback minifiers for non-code formats
- Comment stripping + whitespace compression
- Browser-compatible core (no fs dependency)
- Deterministic output (useful for CI / diffing)
npm install @unsonet/minify-textimport { minifyText } from '@unsonet/minify-text';
const result = await minifyText(`
function test() {
console.log("hello");
}
`, {
filename: 'test.ts'
});
console.log(result);function minifyText(
input: string,
options?: MinifyTextOptions
): Promise<string>type MinifyTextOptions = {
filename?: string;
syntax?: 'auto' | 'js' | 'ts' | 'json' | 'jsonc' | 'html' | 'xml' | 'css' | 'yaml' | 'sql' | 'shell' | 'text';
// terser options (only for js/ts)
ecma?: number;
module?: boolean;
mangle?: boolean;
compress?: boolean | object;
keep_classnames?: boolean;
keep_fnames?: boolean;
};If syntax: 'auto', detection is based on file extension:
file.ts → ts
file.js → js
file.json → json
file.html → htmlFor JavaScript / TypeScript:
- full AST-based minification
- compression enabled (passes: 2)
- optional mangling
- removes comments
- preserves function/class names (by default)
Example:
const result = await minifyText(code, {
filename: 'index.ts',
mangle: false,
});For all other formats:
- parsed and re-stringified (minified)
- collapses whitespace between tags
- removes redundant spaces
- removes whitespace around selectors and rules
- compact whitespace normalization
- safe whitespace collapsing only
- No AST parsing except JS/TS (Terser)
- No regex-based JS manipulation
- Output is always valid for its format
- Safe for browser usage (no Node APIs required in core logic)
await minifyText(`
function sum(a, b) {
return a + b;
}
`, { filename: 'file.js' });await minifyText(`
{
"a": 1,
"b": 2
}
`, { filename: 'data.json' });await minifyText(`
<div>
<span> hello </span>
</div>
`, { filename: 'index.html' });await minifyText(`
body {
margin: 0;
padding: 0;
}
`, { filename: 'style.css' });- predictable output
- no unsafe transformations for non-code files
- JS handled only by real parser (Terser)
- everything else is conservative compression
MIT