JavaScript¶
minify_js makes JavaScript smaller. It removes comments and extra spaces, and the program does the same thing as before. It needs no build step, and it does not rename or rewrite your code. Use it on .js files, or on the <script> blocks of an HTML page. See Minifier if the word is new to you.
Before and after¶
This call minifies a small script and prints the result.
import korpress
src = """// Greeting
/* a
comment */
function greet ( name ) {
const msg = 'Hello, ' + name ; // build it
return msg ;
}
console.log( greet( 'world' ) ) ;
"""
print(korpress.minify_js(src))
function greet(name){const msg='Hello, '+name;return msg}console.log(greet('world'));
The comments, the indentation, the spaces around operators and the ; before } are gone. The names greet, name and msg are the same. The ; at the very end stays (see Options).
What changes¶
| Input | Output | What happened |
|---|---|---|
var a = 1 ; // c/* x */ var b = 2 ; |
var a=1;var b=2; |
comments and spaces removed |
function f ( a , b ) { return a + b ; } |
function f(a,b){return a+b} |
spaces removed, last ; before } removed |
if (x) { y(); } |
if(x){y()} |
same |
a = b + +c; d = e - -f |
a=b+ +c;d=e- -f |
a space is kept where ++ or -- would be read instead |
let c;[1, 2].forEach(f) |
let c;[1,2].forEach(f) |
a line break is removed when it cannot matter |
x = 1y = 2 |
x=1y=2 |
a line break is kept when the language may need it |
#!/usr/bin/env nodevar a = 1 |
#!/usr/bin/env nodevar a=1 |
a first line #! stays |
A // comment ends at the line break. A /* ... */ comment that spans lines counts as a line break, because JavaScript treats it as one. So b = 2 /* x⏎y */ c = 3 keeps a break between 2 and c.
What it never does¶
- No renaming.
unusedLongName,parameterNameandlocalVariablekeep their names. - No dead code removal.
if (false) { never(); }is still there. - No rewriting.
1 + 2is not turned into3,'a' + 'b'is not joined,ifis not turned into&&,varis not turned intolet.
Real output:
korpress.minify_js("function unusedLongName(parameterName) { var localVariable = parameterName; if (false) { never(); } return 1 + 2 }")
function unusedLongName(parameterName){var localVariable=parameterName;if(false){never()}return 1+2}
It is a safety rule: korpress has no syntax tree (a map of how the code is built, which a parser makes), so it cannot prove that a rewrite is safe. See Why it does not rename or remove code.
Options¶
| Option | Default | Effect |
|---|---|---|
keep_important_comments |
True |
keep /*! ... */, @license and @preserve comments |
drop_final_semicolon |
False |
remove the ; that ends the output |
korpress.minify_js("var a = 1 ; var b = 2 ;")
# 'var a=1;var b=2;'
korpress.minify_js("var a = 1 ; var b = 2 ;", drop_final_semicolon=True)
# 'var a=1;var b=2'
The final ; is kept by default because of concatenation. If you join two files with cat a.js b.js, a file that ends without ; can run into the first token of the next one. minify_html turns drop_final_semicolon on for inline scripts, because a <script> block is read alone.
On the command line, --strip-license is keep_important_comments=False, and -t js forces the type when stdin or an odd file name is used. Files with .js, .mjs and .cjs extensions are read as JavaScript. See Command line.
Errors¶
minify_js raises korpress.KorpressError (a ValueError) when it cannot tell where a token ends. Nothing is returned, and a file is not written. The error has .line and .column, both counted from 1, and the message ends with them.
try:
korpress.minify_js("var a = 1;\n/* never closed")
except korpress.KorpressError as err:
print(err) # unterminated comment at line 2, column 1
print(err.line, err.column) # 2 1
The four errors, with the position they point at (where the string, comment, template or expression starts):
| Source | Message |
|---|---|
var a = "oops; |
unterminated string at line 1, column 9 |
var a = 1; then /* never closed |
unterminated comment at line 2, column 1 |
x = `abc ${ 1 |
unterminated template literal at line 1, column 5 |
x = /abc |
unterminated regular expression at line 1, column 5 |
A string that runs to the end of its line without closing is an unterminated string, as in JavaScript. A string with \ and a line break before the closing quote is fine.
Anything else is not an error. korpress does not check that your program is valid. See Limits and safety for what that means, including JSX and TypeScript.
In an HTML page there is no error at all: a script that raises is left as it was. See HTML.
In depth¶
The idea¶
korpress reads the file as a list of tokens, the smallest pieces of code (words, numbers, strings, regular expressions, templates, punctuation). It writes the tokens back with the least separation that keeps the meaning. It does not build a syntax tree. That is why it is fast, and why it can only remove bytes, not rewrite code.
Why it does not rename or remove code¶
The reason is safety. To rename a variable you must know every place that uses it: eval, with, new Function, obj['name'], code in other files that reads a global, and code in a later <script>. To remove dead code you must prove that it is dead. korpress has no syntax tree, so it cannot prove any of this, and it does not guess. A tool like terser or esbuild gives smaller files, because it does parse. korpress gives files that are the same program, token for token.
What it must get right¶
Five cases make a token minifier go wrong. Each one has a test that runs the original and the minified script in Node and compares what they print (see Limits and safety).
Automatic semicolon insertion¶
JavaScript adds a ; at some line breaks when the code would not parse otherwise. If korpress joined those lines, the program would change. It drops a line break only when the token before it cannot end a statement, or the token after it cannot start one. Otherwise it keeps the break. When it is unsure, it keeps the break.
korpress.minify_js("function g() { return\n 42 }")
# 'function g(){return\n42}'
korpress.minify_js("var a = 1\nvar b = 2\na\n++b")
# 'var a=1\nvar b=2\na\n++b'
korpress.minify_js("let a = b\n[1, 2].map(f)")
# 'let a=b\n[1,2].map(f)'
return followed by a break returns undefined, and the 42 is a separate statement: the break after return must stay. a then ++b is two statements, not a++ b. These are the cases the tests cover: return, break, continue, throw, yield, async, a ++ or -- on the next line, a ( or [ on the next line, and class fields without ;.
A break that is safe to remove is removed. After const f = () => {} a ;(function(){})() on the next line needs no break:
korpress.minify_js("const f = () => {\n}\n;(function () {})()")
# 'const f=()=>{};(function(){})()'
A / can start a regular expression or mean a division¶
a / b / c is two divisions. /a\/b/g.test(s) is a regular expression. korpress decides from the token before the /: after a number, a name, ), ] or } it is usually a division. After an operator, (, ,, = or a keyword such as return or typeof it is a regular expression.
) and } are the hard ones, so korpress remembers what each ( and { belonged to. After if (a) the / starts a regular expression. After (a) alone it is a division. After the } of a function declaration it starts a regular expression, after the } of an object literal it is a division:
korpress.minify_js("if (a) /y/.test(s)") # 'if(a)/y/.test(s)'
korpress.minify_js("x = (a) / 2 / 3") # 'x=(a)/2/3'
korpress.minify_js("function f(){}\n/re/.test(s)") # 'function f(){}/re/.test(s)'
korpress.minify_js("x = {}\n/ 2") # 'x={}\n/2'
korpress.minify_js("x = /[/]/.test('/')") # "x=/[/]/.test('/')"
A / inside a character class [...] does not end the regular expression.
Template literals¶
A template literal is copied as it is, spaces and line breaks included. The ${ ... } parts are copied too, but korpress reads them as code, so that a quote, a } or a / inside a nested string or regular expression does not end the template too early.
korpress.minify_js("x = `a ${ b + c } d\n e`")
# 'x=`a ${ b + c } d\n e`'
korpress.minify_js("x = `a ${ 'x'.replace(/x/g, '}') } b`")
# "x=`a ${ 'x'.replace(/x/g, '}') } b`"
Tagged templates (tag`...`) are copied the same way, because the tag function can see the exact text.
Strings and </script>¶
Strings are copied exactly. ' a b ' and " // not a comment " are not touched.
In a .js file, a string like '</script>' is just a string. In an HTML page it is not: the browser ends the script at the first </script> it sees, even inside a string. Write '<\/script>' in your scripts.
korpress adds one more check for HTML. After it minifies an inline <script>, it looks at the result. If the result contains </script, or <!--, it throws the result away and keeps your original script. This can happen because removing spaces joins tokens:
js = "x = a < /script/.test(b);\ny = 1 ;"
korpress.minify_js(js)
# 'x=a</script/.test(b);y=1;'
korpress.minify_html(f"<script>\n{js}\n</script>")
# '<script>\nx = a < /script/.test(b);\ny = 1 ;\n</script>'
Alone, the minified code is fine. Inside <script>, a</script/ would close the element. The script is left as it was, and no error is raised. The same check runs for <style> and </style.
License comments¶
/*! ... */ comments, and comments that contain @license or @preserve, are kept. They are written on their own line.
korpress.minify_js("/*! MyLib v1 | MIT */\nvar a = 1 ; /* other */")
# '/*! MyLib v1 | MIT */\nvar a=1;'
korpress.minify_js("/**\n * @license MIT\n */\nvar a = 1")
# '/**\n * @license MIT\n */\nvar a=1'
A license comment is kept only when it already sits on its own line (or at the start of the file). In the middle of a line, such as var a = 1 /*! inline */ ; var b, korpress removes it, because putting a line break there could change the meaning. Pass keep_important_comments=False to drop all of them.
Next: Limits and safety