All files executeLess.ts

50% Statements 12/24
62.5% Branches 5/8
33.33% Functions 3/9
50% Lines 12/24

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80            1x                                                                             6x 6x 6x 6x                 6x 6x 4x   6x 6x 4x     6x                          
import fs from 'fs-extra';
import less from 'less';
import { spawn } from 'child_process';
// @ts-ignore
import LessPluginAutoPrefix from 'less-plugin-autoprefix';
 
const autoprefixPlugin = new LessPluginAutoPrefix({
  browsers: [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
});
 
export interface IOutputFile extends Less.RenderOutput {
  path: string;
  less?: string;
}
 
 
export function execute(command: string) {
  return new Promise((resolve, reject) => {
    const subProcess = spawn('bash');
    function onData(data: string | Buffer | Uint8Array) {
      process.stdout.write(data);
    }
    subProcess.on('error', (error: { message: any; }) => {
      reject(new Error(`command failed: ${command}; ${error.message ? error.message : ''}`));
    });
    subProcess.stdout.on('data', onData);
    subProcess.stderr.on('data', onData);
    subProcess.on('close', (code: {} | PromiseLike<{}> | undefined) => {
      resolve(code);
    });
    subProcess.stdin.write(`${command} \n`);
    subProcess.stdin.end();
  });
}
 
export type ExecuteLessOptions = Less.Options & {
  rmGlobal?: boolean;
}
 
export function executeLess(lessPath: string, options?: ExecuteLessOptions): Promise<IOutputFile> {
  const lessStr = fs.readFileSync(lessPath);
  const { rmGlobal, ...other } = options || {};
  return new Promise((resolve, reject) => {
    const options: Less.Options = {
      depends: false,
      compress: false,
      lint: false,
      plugins: [autoprefixPlugin as Less.Plugin],
      ...other,
      filename: lessPath,
    }
 
    let lessStrTo = lessStr.toString();
    if (rmGlobal) {
      lessStrTo = lessStrTo.replace(/:global\((.*)\)/g, '$1');
    }
    less.render(lessStrTo, options).then((output: Less.RenderOutput) => {
      if (rmGlobal) {
        output.css = output.css.replace(/:global\s+\{([\s\S]*?)(\s.+)?\}/g, '')
          .replace(/(:global\s+)|(\s.+:global\s+)/g, '')
      }
      resolve({
        less: lessStr.toString(),
        path: lessPath,
        // css: '',
        // map: 'string',
        // imports: [],
        ...output,
      });
    }).catch((e: any) => {
      reject(e);
    });
  });
}