UNPKG

bestikk-uglify

Version:

A simple tool to uglify JavaScript files based on Google Closure Compiler

90 lines (83 loc) 2.66 kB
'use strict' const log = require('bestikk-log') const childProcess = require('child_process') const javaSemanticVersion = function () { const result = childProcess.execSync('java -version 2>&1', { encoding: 'utf8' }) return extractJavaSemanticVersion(result) } const extractJavaSemanticVersion = function (input) { const lines = input.split('\n') let javaVersionLine for (const line of lines) { if (line.startsWith('java version') || line.startsWith('openjdk version')) { javaVersionLine = line } } if (javaVersionLine) { const javaVersion = javaVersionLine.match(/"(.*?)"/i)[1] let semanticVersion if (javaVersion.indexOf('.') === -1) { // Check if version is formatted as number semanticVersion = [null, javaVersion, 0, 0] } else { semanticVersion = javaVersion.match(/([0-9]+)\.([0-9]+)\.([0-9]+)(_.*)?/i) } const major = parseInt(semanticVersion[1]) const minor = parseInt(semanticVersion[2]) const patch = parseInt(semanticVersion[3]) const meta = semanticVersion[4] if (major === 1) { return { major: minor, minor: patch, patch: parseInt(meta.replace(/_/g, '')) } } else { return { major, minor, patch } } } throw new Error('Unable to find the java version in: ' + lines) } const checkRequirements = function () { // Java 8 or higher must be available in PATH try { const semanticVersion = javaSemanticVersion() if (semanticVersion.major < 8) { log.error('Closure Compiler requires Java 8 or higher') return false } } catch (e) { log.error('error: ' + e) log.error('\'java\' binary is not available in PATH') return false } return true } class Uglify { constructor (args) { this.requirementSatisfied = checkRequirements() this.compilerJar = 'closure-compiler-v20190215.jar' this.args = args || ['--warning_level=QUIET'] } async minify (source, destination) { if (this.requirementSatisfied) { return new Promise((resolve, reject) => { // eslint-disable-next-line n/no-path-concat childProcess.exec(`java -jar ${__dirname}/${this.compilerJar} ${this.args.join(' ')} --js_output_file=${destination} ${source}`, error => { if (error) { log.error('error: ' + error) return reject(error) } return resolve({}) }) }) } log.warn('Requirements are not satisfied (see previous errors), skipping minify task') return {} } } module.exports = Uglify module.exports._extractJavaSemanticVersion = extractJavaSemanticVersion