compress.ts 1.0 KB
Newer Older
V
vben 已提交
1 2 3
import { gzip } from 'zlib';
import { readFileSync, writeFileSync } from 'fs';
import { GzipPluginOptions } from './types';
4
import { readAllFile, getCwdPath, isBuildGzip, isSiteMode } from '../../../utils';
V
vben 已提交
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

export function startGzip(
  fileContent: string | Buffer,
  options: GzipPluginOptions = {}
): Promise<Buffer> {
  return new Promise((resolve, reject) => {
    gzip(fileContent, options.gzipOptions || {}, (err, result) => {
      if (err) {
        reject(err);
      } else {
        resolve(result);
      }
    });
  });
}

// 手动压缩css
export async function startGzipStyle() {
  if (isBuildGzip() || isSiteMode()) {
24 25
    const outDir = 'dist';
    const assets = '_assets';
V
vben 已提交
26 27 28 29 30 31 32 33 34 35
    const allCssFile = readAllFile(getCwdPath(outDir, assets), /\.(css)$/);
    for (const path of allCssFile) {
      const source = readFileSync(path);
      const content = await startGzip(source);
      const ds = path.split('/');
      const fileName = ds[ds.length - 1];
      writeFileSync(getCwdPath(outDir, assets, `${fileName}.gz`), content);
    }
  }
}