🔗 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
Copied!
2. Create HTML Minfier Middleware
node ace make:middleware HtmlMinifier
Copied!
2. Register Global Middleware
Server.middleware.register([ () => import('@ioc:Adonis/Core/BodyParser'), () => import('App/Middleware/HtmlMinifier') ])
Copied!
- start
- kernel.ts
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) } }
Copied!
Join The Discussion! (0 Comments)
Please sign in or sign up for free to join in on the dicussion.
Be the first to Comment!