-
Notifications
You must be signed in to change notification settings - Fork 50
Expand file tree
/
Copy pathindex.ts
More file actions
51 lines (45 loc) · 1.59 KB
/
index.ts
File metadata and controls
51 lines (45 loc) · 1.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*!
* node-minify
* Copyright (c) 2011-2026 Rodolphe Stoclin
* MIT Licensed
*/
import type { CompressorResult, MinifierOptions } from "@node-minify/types";
import {
ensureStringContent,
extractSourceMapOption,
} from "@node-minify/utils";
import { transform } from "esbuild";
/**
* Minifies JavaScript or CSS content using esbuild according to the provided settings.
*
* @param settings - Minification settings; `settings.type` must be `"js"` or `"css"`. Optional `settings.options` are passed to esbuild.transform (except `sourceMap` which is handled separately).
* @param content - Input content to be minified; will be converted to a string if necessary.
* @returns An object with `code` containing the minified output and `map` containing the source map if produced, otherwise `undefined`.
* @throws Error if `settings.type` is missing or not `"js"` or `"css"`.
*/
export async function esbuild({
settings,
content,
}: MinifierOptions): Promise<CompressorResult> {
const contentStr = ensureStringContent(content, "esbuild");
if (
!settings?.type ||
(settings.type !== "js" && settings.type !== "css")
) {
throw new Error("You must specify a type: js or css");
}
const loader = settings.type === "css" ? "css" : "js";
const { sourceMap, restOptions } = extractSourceMapOption(
settings?.options
);
const result = await transform(contentStr, {
loader,
minify: true,
sourcemap: sourceMap,
...restOptions,
});
return {
code: result.code,
map: result.map || undefined,
};
}