farm-plugin-static-opt
v0.2.0
Published
Static optimization plugin for FarmFE — constant folding, loop unrolling, dead branch elimination at compile time
Maintainers
Readme
farm-plugin-static-opt
Static optimization plugin for FarmFE — performs compile-time optimizations that JS engines would otherwise do at runtime.
Install
npm install farm-plugin-static-optDependencies: This plugin uses core-ast-ts internally. Installed automatically.
Concept
This is not minification. This is compile-time static optimization — doing at build time what JS engines do at runtime:
- Constant folding:
2 + 3→5,"hello" + " world"→"hello world" - Dead branch elimination:
if (true) { A } else { B }→A - Loop unrolling:
for (let i = 0; i < 3; i++) { ... }→ body × 3
This makes the output code smaller and faster before any minifier even sees it.
Usage
import staticOpt from 'farm-plugin-static-opt'
export default {
plugins: [staticOpt()],
}With options:
staticOpt({
constantFolding: true, // fold 2+3 → 5 (default: true)
deadBranchElimination: true, // remove if(false) branches (default: true)
loopUnrolling: true, // unroll small loops (default: true)
maxUnroll: 8, // max trip count for unrolling (default: 8)
})Optimizations
Constant Folding
Arithmetic, logical, and bitwise expressions with all-literal operands are evaluated at compile time:
// Before
const area = 3.14 * 4 * 4
const flag = true && false
const mask = 0xFF & 0x0F
// After
const area = 50.24
const flag = false
const mask = 15String concatenation:
// Before
const url = "/api" + "/v1" + "/users"
// After
const url = "/api/v1/users"Dead Branch Elimination
If/else and ternary with constant conditions:
// Before
if (true) {
setupApp()
} else {
setupFallback()
}
// After
setupApp()// Before
const mode = false ? 'production' : 'development'
// After
const mode = 'development'Works especially well combined with farm-plugin-selective — after selective compilation replaces conditions with literals, this plugin eliminates the dead branches.
Loop Unrolling
For-loops with known bounds and small trip counts:
// Before
for (let i = 0; i < 3; i++) {
console.log(i)
}
// After
{
console.log(0)
console.log(1)
console.log(2)
}With step:
// Before
for (let i = 0; i < 6; i += 2) {
process(i)
}
// After
{
process(0)
process(2)
process(4)
}Only unrolls loops with:
- Literal start, end, and step values
- Trip count ≤
maxUnroll(default: 8) - Simple
i++/i--/i += N/i -= Nupdate
HMR
Optimizations are re-applied on file changes.
License
MIT
