kaven-utils
Version:
Utils for Node.js.
113 lines (112 loc) • 4.03 kB
JavaScript
/********************************************************************
* @author: Kaven
* @email: kaven@wuwenkai.com
* @website: http://blog.kaven.xyz
* @file: [Kaven-Utils] /src/KavenUtility.Minify.ts
* @create: 2024-05-24 11:25:23.824
* @modify: 2024-11-01 14:38:14.468
* @version: 5.4.5
* @times: 7
* @lines: 136
* @copyright: Copyright © 2024 Kaven. All Rights Reserved.
* @description: [description]
* @license: [license]
********************************************************************/
import { existsSync } from "node:fs";
import { readFile, readdir, stat, unlink, writeFile } from "node:fs/promises";
import { basename, extname, join } from "node:path";
import { minify } from "terser";
import { KavenLogger } from "./KavenLogger.js";
/**
*
* @since 5.4.3
* @version 2024-05-24
*/
export async function Minify(options) {
const list = typeof options.src === "string" ? [options.src] : options.src;
while (list.length > 0) {
const file = list.shift();
if (!file) {
continue;
}
let stats;
try {
stats = await stat(file);
}
catch (err) {
KavenLogger.Default.Warn(`Error getting stats for file ${file}:`, err);
continue;
}
if (stats.isFile()) {
const ext = extname(file).toLowerCase();
const fileLowercase = file.toLowerCase();
if (fileLowercase.endsWith(".d.ts")) {
if (options.deleteTypeScriptDeclarationFile) {
if (options.trace) {
KavenLogger.Default.Info(`Delete: ${file}`);
}
await unlink(file);
}
continue;
}
if (fileLowercase.endsWith(".js.map")) {
if (options.deleteSourceMap) {
if (options.trace) {
KavenLogger.Default.Info(`Delete: ${file}`);
}
await unlink(file);
}
continue;
}
if (ext !== ".js") {
continue;
}
const code = await readFile(file, "utf8");
const terserOptions = {
format: {
ecma: 2015,
comments: false,
},
};
const mapFile = file + ".map";
if (existsSync(mapFile)) {
const content = await readFile(mapFile, "utf8");
terserOptions.sourceMap = {
content,
};
if (options.setSourceMappingURL !== false) {
terserOptions.sourceMap.url = basename(mapFile);
}
}
const terserResult = await minify(code, {
...terserOptions,
...options?.terserOptions,
});
if (terserResult.code) {
await writeFile(file, terserResult.code, "utf8");
if (options?.trace) {
KavenLogger.Default.Info(`Minifying ${file} success.`);
}
if (typeof terserResult.map === "string") {
await writeFile(mapFile, terserResult.map, "utf8");
if (options?.trace) {
KavenLogger.Default.Info(`Source map: ${mapFile}.`);
}
}
}
}
else if (stats.isDirectory()) {
if (!options.includeNodeModules) {
const dir = basename(file);
if (dir.toLowerCase() === "node_modules") {
if (options.trace) {
KavenLogger.Default.Warn(`Ignore: ${file}`);
}
continue;
}
}
const files = await readdir(file);
list.push(...files.map(p => join(file, p)));
}
}
}