Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.
Hello, I’m Shanyue.
This is my front end engineering knowledge card collection 10/36 published in Nuggets
The AST analysis is used to generate a smaller AST and generate code according to some strategies. At present, terser is used for JS code compression in front-end engineering.
There are several common ways to compress AST:
Remove redundant characters: Spaces, line feeds, and comments
// Sum the two numbers
function sum (a, b) {
return a + b;
}
Copy the code
At this point, the file size is 62 bytes, and generally Chinese takes up more space.
Extra white space characters can take up a lot of volume, such as Spaces, newlines, and comments. When we remove all the white space matching comments, the code size is reduced.
After removing extra characters, the file size is 30 bytes. The compressed code is as follows:
function sum(a,b){return a+b}
Copy the code
What happens when you replace redundant characters?
For example, if multiple lines of code are compressed into one line, note the semicolon at the end of the line.
Compressed variable name: variable name, function name, and attribute name
function sum (first, second) {
return first + second;
}
Copy the code
If first and second are in the scope of the function, they are not referred to outside the scope, so you can make their variable names shorter. But what if this were a module and the sum function would not be exported? I can shorten this function name as well.
// Compress: shorten the variable name
function sum (x, y) {
return x + y;
}
// Recompress: remove empty characters
function s(x,y){return x+y}
Copy the code
In this example, when code compression (COMPRESS) is done, code obfuscation (mangle) is also done. However, shortening variable naming also requires AST support to avoid naming conflicts in scope.
Parsing program logic: merge declaration and Boolean simplification
By analyzing the code logic, you can rewrite your code to a more concise form.
The following is an example of a merge declaration:
/ / before compression
const a = 3;
const b = 4;
/ / after the compression
const a = 3, b = 4;
Copy the code
An example of Boolean simplification is as follows:
/ / before compression! b && ! c && ! d && ! e/ / after the compression! (b||c||d||e)Copy the code
Parsing program logic: compile the forecast
Computations are performed at compile time to reduce runtime computations, as shown in the following example:
/ / before compression
const ONE_YEAR = 365 * 24 * 60 * 60
/ / after the compression
const ONE_YAAR = 31536000
Copy the code
And a more complex example, which is a mace level optimization.
/ / before compression
function hello () {
console.log('hello, world')
}
hello()
/ / after the compression
console.log('hello, world')
Copy the code