JS and CSS minifier

Post your working scripts, libraries and tools for AHK v1.1 and older
john_c
Posts: 493
Joined: 05 May 2017, 13:19

JS and CSS minifier

25 Feb 2021, 04:35

JS and CSS minifier.

1. Removes // and /**/ comments
2. Optionally, converts a file to a one-liner

Usage example: minifier(["minifier-tests.js"], false, "min")

Tested (see the tests below), but if you need a bulletproof reliable solution, you should use something different, probably https://github.com/RnbWd/gulp-strip-comments. Bug reports are welcome.

Code: Select all

setWorkingDir, % a_scriptDir
fileEncoding, utf-8

minifier(targets, oneLiner := true, dir := ".") {
  i := 0
  for index, target in targets {
    fileRead, contents, % target
    if (contents == "") {
      i += 1
      missing .= "`r`n" . i . a_tab . target
    }
    else {
      ; https://stackoverflow.com/q/49178646
      ; https://stackoverflow.com/a/36328890
      ; https://stackoverflow.com/q/66301705
      ; https://stackoverflow.com/q/66322316
      ; https://stackoverflow.com/q/3469080 - \h
      ; https://stackoverflow.com/q/3219014 - \R
      regEx1 = ((?:["'][^"']*\/\/.*?["'])|(?:https?:\/\/.*?[\w./]+))|\/\/.*
      contents := regExReplace(contents, regEx1, "$1") ; removes // comments
      regEx2 = (["'][^\r\n]*\/\*.*?\*\/[^\r\n]*["'])|\/\*(?:.|\r?\n)*?\*\/
      contents := regExReplace(contents, regEx2, "$1") ; removes /**/ comments
      contents := regExReplace(contents, "m)\h+$") ; removes trailing whitespace
      if (oneLiner)
        contents := regExReplace(contents, "\R\h*") ; removes indents and line breaks
      else {
        ; removes empty lines
        contents := regExReplace(contents, "(\R){2,}", "$1")
        contents := regExReplace(contents, "(^\R|\R$)")
      }

      ; msgBox,,, % contents ; for testing
      dir := regExReplace(dir, "\\?$") . "\"
      if (!inStr(fileExist(dir), "d"))
        fileCreateDir, % dir
      minified := dir . regExReplace(target, "\.(.+)$", ".min.$1")
      file := fileOpen(minified, "w"), file.write(contents), file.close()
    }
  }

  if (missing != "")
    msgBox,,, % "No such files or the files are empty:" . missing
}

minifier(["minifier-tests.js"], false, "min")
tests:

Code: Select all




//
// remove
// remove
//

// remove

alert('// keep');

alert('aaa // keep');

alert(x); // remove



/**
 * remove
 * remove
 */

/* remove */

/**/ alert(y); /**/

const x = 'url(https://site.xyz/aaa.html) /* keep */';

alert('/* keep */');

alert('aaa /* keep */ bbb');

alert('aaa' + 'aaa /* keep */ bbb' + 'bbb');

alert("/* keep */");

// remove

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: emandreck and 255 guests