jbaylina jbaylina - 22 days ago 7
Javascript Question

How to generate a single optimized html file from web a project?

I have a typical web page with a single html file. This page uses css, javascript modules (requirejs) and images. I would like to generate a single html file containing all the resources embedded and minified including the html file itself.

This is the structure that I have:

myApp/
www/
css/
css1.css
css2.css
img/
img1.png
img2.png
js/
main.js
module1.js
index.html


And I would like to generate this:

myApp/
www-build/
index.min.html


I know that exists different tools to optimize javascripts, css and html. But the question is how to assemble them in a single file automaticaly.

Answer

I ended up using gruntjs and a series of grunt tasks to do the job:

  • A Jade template with the include directive to import js and css.
  • grunt-base64 To convert the images to base64.

The jade file, would be some thing like this:

html
    head
        title= "Example Page"
        include css/css1.css
        include css/css2.css
        include js/main.js
        include js/module1.js

    body
        | <img src="data:image/png;base64,
        include img1.b64
        | "/>

        | <img src="data:image/png;base64,
        include img2.b64
        | "/>

        canvas#myCanvas 

I also used uglify and other excellent predefined tasks to optimize the code.