Your first minified site¶
You will make the files of a small site smaller: first a few strings, then one file, then a whole folder. You finish with what to check before the result goes online. You need basic Python and nothing else. For the command line tool, see the command line page.
Minifying means removing the bytes a browser does not need: spaces, line breaks and comments. The page looks and works the same, and the files are smaller, so they load faster.
1. Install¶
A virtual environment keeps this project's packages apart from the others. Create one, then install korpress:
mkdir mysite && cd mysite
python -m venv .venv && source .venv/bin/activate # Windows: .venv\Scripts\activate
pip install --pre korpress
Check that it works:
korpress --version
korpress 0.1.0
2. Minify a string¶
Each kind of code has its own function. Each takes a string and returns a
shorter string. Create try.py:
import korpress
print(korpress.minify_css("a { color : red ; margin : 0px }"))
print(korpress.minify_js("var a = 1 ; // hi\nvar b = a + 1"))
print(korpress.minify_html("<div>\n <p> Hello <b>you</b> </p>\n</div>"))
Run python try.py:
a{color:red;margin:0}
var a=1;var b=a+1
<div><p>Hello <b>you</b></p></div>
Look at what changed:
- CSS lost its spaces and its last
;.0pxbecame0. - JS lost its comment and its spaces. The
;between the two statements stays, because the code needs it. - HTML lost the line breaks between the tags. The space between
Helloand<b>stays, because a browser shows it.
When the kind is only known at run time, use minify with the kind as a
second argument. It gives the same result:
print(korpress.minify("a { color : red ; }", "css")) # a{color:red}
The kind is "html", "css" or "js". Anything else raises ValueError:
ValueError: unknown kind 'txt', expected 'html', 'css' or 'js'
Options¶
Each function takes keyword options. A few examples:
print(korpress.minify_css("/*! MIT */ a { color : #ffffff }"))
print(korpress.minify_css("/*! MIT */ a { color : #ffffff }", keep_important_comments=False))
print(korpress.minify_html("<!-- c --><p> a </p><style>a { color : red }</style>"))
print(korpress.minify_html("<!-- c --><p> a </p><style>a { color : red }</style>", remove_comments=False, minify_css=False))
/*! MIT */a{color:#fff}
a{color:#fff}
<p>a</p><style>a{color:red}</style>
<!-- c --><p>a</p><style>a { color : red }</style>
A comment that starts with /*! is a license comment. korpress keeps it by
default, because a license often has to stay in the file. The other options
are:
| Function | Keyword options |
|---|---|
minify_html |
collapse_whitespace=True, remove_comments=True, minify_css=True, minify_js=True |
minify_css |
keep_important_comments=True |
minify_js |
keep_important_comments=True, drop_final_semicolon=False |
drop_final_semicolon=True removes the very last ; of a script:
print(korpress.minify_js("var a = 1;\nvar b = 2;\n"))
print(korpress.minify_js("var a = 1;\nvar b = 2;\n", drop_final_semicolon=True))
var a=1;var b=2;
var a=1;var b=2
3. Minify a file¶
Create style.css:
/* Main styles */
body {
margin : 0px ;
color : #ffffff ;
}
h1 {
font-size : 2em ;
}
minify_file reads a file, minifies it and writes the result to a second
file. It returns the size before and after, in bytes:
before, after = korpress.minify_file("style.css", "style.min.css")
print(before, after) # 98 42
The kind comes from the extension: .html and .htm are HTML, .css is
CSS, .js, .mjs and .cjs are JS. If korpress cannot guess it, you get
a ValueError:
ValueError: cannot guess the type of style.txt, pass kind=
Pass kind to say it yourself:
korpress.minify_file("style.txt", "style.min.css", kind="css")
Missing folders in the second argument are created. If you leave the second argument out, the file is overwritten in place. The result is written to a temporary file first and then moved, so a failure never leaves a half written file.
korpress.kind_of(path) gives the kind of a file name, or None. The file
does not need to exist.
4. Minify a whole static folder¶
A site is a folder with HTML, CSS, JS and other files. Make this tree:
site/
index.html
css/main.css
css/lib.min.css
js/app.js
img/logo.png
index.html is:
<!DOCTYPE html>
<html>
<head>
<!-- page title -->
<title>Hello</title>
<style>
p { color : red ; }
</style>
</head>
<body>
<p> Hello <b>you</b> </p>
<script>
var a = 1 ;
</script>
</body>
</html>
css/main.css is the style.css from step 3, and js/app.js is:
// Greets the user
function greet(name) {
console.log("Hello, " + name) ;
}
greet("world") ;
The quickest way is one command. It minifies the three kinds, and --copy
copies the other files, like the image:
korpress site/ -o public/ --copy
site/css/main.css: 98 -> 42 B (-57.1%)
site/index.html: 247 -> 148 B (-40.1%)
site/js/app.js: 98 -> 64 B (-34.7%)
total: 3 files, 443 -> 254 B (-42.7%)
public/ now has the same tree as site/. The file lib.min.css was
copied as it is: a file with .min. in its name is already minified, so
korpress does not touch it.
If you want control from Python, for example to run it in a build script,
do the same with a loop. Create build.py:
import shutil
from pathlib import Path
import korpress
SRC = Path("site")
DST = Path("public")
total_before = total_after = 0
for path in sorted(SRC.rglob("*")):
parts = path.relative_to(SRC).parts
if not path.is_file() or any(p.startswith(".") or p == "node_modules" for p in parts):
continue
out = DST / path.relative_to(SRC)
kind = None if ".min." in path.name else korpress.kind_of(path)
if kind is None: # an image, or a file that is already minified: copy it
out.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(path, out)
continue
try:
before, after = korpress.minify_file(path, out)
except korpress.KorpressError as e:
print(f"{path}: line {e.line}, column {e.column}: {e}")
continue
total_before += before
total_after += after
print(f"{path}: {before} -> {after} bytes")
print(f"total: {total_before} -> {total_after} bytes")
site/css/main.css: 98 -> 42 bytes
site/index.html: 247 -> 148 bytes
site/js/app.js: 98 -> 64 bytes
total: 443 -> 254 bytes
The loop skips hidden folders (like .git) and node_modules, as the
command line tool does.
5. Errors¶
CSS and HTML never raise an error. korpress minifies what it understands and
leaves the rest as it is. JS can fail, because korpress has to know where a
string, a comment, a template or a regular expression ends. An unterminated
one raises KorpressError:
try:
korpress.minify_js("var s = 'abc;\nvar t = 1")
except korpress.KorpressError as e:
print(e)
print(e.line, e.column)
print(isinstance(e, ValueError))
unterminated string at line 1, column 9
1 9
True
KorpressError is a ValueError. .line and .column say where the
problem starts, counted from 1. That is the line to open in your editor.
In the loop of step 4, a broken app.js is reported and the other files
still go through:
site-bad/app.js: line 1, column 9: unterminated string at line 1, column 9
site-bad/index.html: 247 -> 148 bytes
total: 247 -> 148 bytes
(That run was on a folder named site-bad/, with the SRC of the script
changed to match, that held index.html and a broken app.js.)
The command line does the same and exits with code 1. See exit codes.
6. Before you deploy¶
korpress is in alpha. It checks the tokens it knows, but it does not parse your JS, so look at the result before you publish it:
- Keep your sources. Write the result to another folder (
-o public/), not over the files you edit. Do not use--in-placeon a folder under version control that you have not committed. - Compare in a browser. Open the original site and the minified site side by side. Click through the main pages. Check the layout, the forms and the menus.
- Open the console. In the browser's developer tools, look for errors in the console and for failed requests in the network tab. A script that breaks shows up there first.
- Diff the HTML. Broken HTML is minified, not repaired. Removing the
spaces between tags can change how a malformed page is parsed, for
example with an unclosed
<a>. If a page looks different, fix the HTML. - Know the limits. JS is not renamed and dead code is not removed, so do not expect the size of a bundler. JSX, TypeScript and Flow are not supported: compile them to plain JS first.
- Measure. The sizes printed on screen tell you if it was worth it.
If a file looks wrong, minify it alone and compare it with the original.
--no-css, --no-js and --keep-comments turn off parts of the HTML
minifier to find the cause.
What to read next¶
- Command line: every option of
korpress, with examples. - HTML, CSS: what each minifier changes, and what it leaves alone.