AdonisJS Quick Tip #12.0
Minify Your AdonisJS HTML in 5 Minutes
We'll learn how we can alter all our AdonisJS HTML response bodies using a simple global middleware to add HTML minification.
🔗 HTML Minifier Package: https://github.com/kangax/html-minifier
🕑 Chapters
- What's The Default Behavior
- Install HTML Minifier
- How To Alter Response Body
- HTML Minfier Middleware
- Inspecting What It's Doing
- Limiting Middleware Execution
- Testing Our HTML Minification Middleware
- Outro
1. Install HTML Minifier Package
npm i html-minifier
2. Create HTML Minfier Middleware
node ace make:middleware HtmlMinifier
2. Register Global Middleware
// start/kernel.ts
Server.middleware.register([
() => import('@ioc:Adonis/Core/BodyParser'),
() => import('App/Middleware/HtmlMinifier')
])
3. HTML Minifier Middleware
import type { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
const minify = require('html-minifier').minify
export default class HtmlMinifier {
public async handle({ request, response }: HttpContextContract, next: () => Promise<void>) {
// BEFORE NEXT: altering, authorizing, preparing request
await next()
// AFTER NEXT: altering response
const method = request.method()
const accepts = request.accepts([]) ?? [] as string[]
const isXml = request.url().endsWith('.xml')
// if not GET request or doesn't expect HTML or is XML, then exit
// since await next() already ran, we're safe to just return here to exit
if (method !== 'GET' || !accepts.includes('text/html') || isXml) {
return
}
// get the minified HTML of our current response body
const minifiedBody = minify(response.getBody(), {
minifyCss: true,
minifyJs: true,
removeComments: true,
collapseWhitespace: true
})
// set minfied HTML as new response body
response.send(minifiedBody)
}
}
Join The Discussion! (0 Comments)
Please sign in or sign up for free to join in on the dicussion.