59 lines
1.9 KiB
JavaScript
59 lines
1.9 KiB
JavaScript
/**
|
||
* 构建后预压缩:为 dist 下的文本资源生成 .br / .gz 副本。
|
||
*
|
||
* 后端静态服务(backend/api/router.go)会按 Accept-Encoding 直接返回预压缩文件,
|
||
* 省掉每个请求的实时压缩开销,也避免引入压缩中间件依赖。
|
||
*/
|
||
import { createReadStream, createWriteStream, readdirSync, statSync } from 'node:fs'
|
||
import { extname, join } from 'node:path'
|
||
import { fileURLToPath } from 'node:url'
|
||
import { pipeline } from 'node:stream/promises'
|
||
import { createGzip, createBrotliCompress, constants as zlibConstants } from 'node:zlib'
|
||
|
||
const distDir = fileURLToPath(new URL('../dist/', import.meta.url))
|
||
const COMPRESSIBLE = new Set(['.html', '.js', '.css', '.svg', '.json', '.txt', '.webmanifest'])
|
||
const MIN_BYTES = 1024
|
||
|
||
/** @param {string} dir @returns {string[]} */
|
||
function walk(dir) {
|
||
return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
|
||
const full = join(dir, entry.name)
|
||
return entry.isDirectory() ? walk(full) : [full]
|
||
})
|
||
}
|
||
|
||
/**
|
||
* @param {string} file
|
||
* @param {'br' | 'gz'} suffix
|
||
* @param {() => import('node:stream').Transform} factory
|
||
*/
|
||
async function writeCompressed(file, suffix, factory) {
|
||
await pipeline(createReadStream(file), factory(), createWriteStream(`${file}.${suffix}`))
|
||
}
|
||
|
||
let fileCount = 0
|
||
let sourceBytes = 0
|
||
|
||
for (const file of walk(distDir)) {
|
||
if (!COMPRESSIBLE.has(extname(file).toLowerCase())) continue
|
||
const size = statSync(file).size
|
||
if (size < MIN_BYTES) continue
|
||
|
||
await writeCompressed(file, 'gz', () => createGzip({ level: 9 }))
|
||
await writeCompressed(file, 'br', () =>
|
||
createBrotliCompress({
|
||
params: {
|
||
[zlibConstants.BROTLI_PARAM_QUALITY]: 11,
|
||
[zlibConstants.BROTLI_PARAM_SIZE_HINT]: size,
|
||
},
|
||
}),
|
||
)
|
||
|
||
fileCount += 1
|
||
sourceBytes += size
|
||
}
|
||
|
||
console.log(
|
||
`precompress: ${fileCount} 个文件生成 .br/.gz 预压缩副本(源文件共 ${(sourceBytes / 1024).toFixed(1)} KB)`,
|
||
)
|