Serving Static HTML With Nodjs And Grunt For Template-Development
A Simple Nodejs/Grunt-Development-Environment for static HTML-Templates
Nowadays, frontend-development is mostly done with Nodjs and Grunt. On npm, there are plenty of useful plugin’s, that ease the development of HTML and CSS. For example grunt-contrib-less to automate the compilation of LESS-sourcecode to CSS, or grunt-svgstore to pack several SVG-graphics in a single SVG-sprite.
Because of that, I decided to switch to Nodejs and Grunt to develop the HTML- and CSS-Markup for the templates, that I need for my Spring/Thymeleaf-Applications. But as with everything new, I had some hard work, to plug together what I needed. In this article I want to share, how I have set up a really minimalistic, but powerful development-environment for static HTML-templates, that suites all of my initial needs.
This might not be the best solutions, but it is a good starting point for beginners like me and it is here to be improved through your feedback!
You can browse the example-development-environment on juplo.de/gitweb, or clone it with:
git clone http://juplo.de/git/examples/template-development
After installing npm you have to fetch the dependencies with:
npm install
Than you can fire up a build with:
grunt
…or start a webserver for development with:
git run-server
Serving The HTML and CSS For Local Development
The hardest part while putting together the development-environment was my need to automatically build the static HTML and CSS after file-changes and serve them via a local webserver.
As I wrote in an earlier article, I often stumble over problems, that arise from the Same-origin policy when accessing the files locally through file:///
-URI’s).
I was a bit surprised, that I could not find a simple explanation, how to set up a grunt-task to build the project automatically on file-changes and serve the generated HTML and CSS locally. That is the main reason, why I am writing this explanation now, in order to fill that gap ;)
I realised that goal by implemnting a grunt-task, that spawn’s a process that uses the http-server to serve up the files and combine that task with a common watch-task:
grunt.registerTask('http-server', function() {
grunt.util.spawn({
cmd: 'node_modules/http-server/bin/http-server',
args: [ 'dist' ],
opts: { stdio: 'inherit' }
});
});
grunt.registerTask('run-server', [ 'default', 'http-server', 'watch' ]);
The rest of the configuration is really pretty self-explaining. I just put together the pieces I needed for my template development (copy some static HTML and generate CSS from the LESS-sources) and configured grunt-contrib-watch to rebuild the project automatically, if anything changes.
The result is put under dist/
and is ready to be included in my Spring/Thymeleaf-Application as it is.