-
Adonis doesn't minify HTML output by default. I know view templates are compiled and optionally cached. I am looking for some guidance on where and how to tap into that process to add an additional step with something like HTML minifier. |
Beta Was this translation helpful? Give feedback.
Answered by
tomgobich
Apr 7, 2022
Replies: 1 comment 1 reply
-
You can apply a global middleware, check to ensure it matches your requests with HTML output, and minify it within there. Place all your logic after import { HttpContextContract } from '@ioc:Adonis/Core/HttpContext'
const minify = require('html-minifier').minify;
export default class HtmlMinify {
public async handle({ response, request }: HttpContextContract, next: () => Promise<void>) {
// code for middleware goes here. ABOVE THE NEXT CALL
await next()
const method = request.method()
const accepts = request.accepts([]) ?? [] as string[]
if (method === 'GET' && accepts.includes('text/html')) {
const minified = minify(response.getBody(), {
minifyCss: true,
minifyJs: true,
removeComments: true,
preserveLineBreaks: true,
collapseInlineTagWhitespace: true,
collapseWhitespace: true
})
response.send(minified)
}
}
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
galaczi
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can apply a global middleware, check to ensure it matches your requests with HTML output, and minify it within there. Place all your logic after
await next()
and it'll run at the end of your request instead of at the start.