LoginSignup
0
0

More than 5 years have passed since last update.

grunt-contrib-watchのlivereloadでどんなHTMLにも対応する

Posted at

メモ。

HTMLへのアクセスのとき、HTMLの末尾にLiveReload用のスクリプトを勝手に追加して返す。</html>とかの位置を無視するのでお行儀良くないけども、まあ開発用だから良いかなーと。

Gruntfile.js
module.exports = function(grunt) {
    grunt.initConfig({
        express: {
            dev: {
                options: {
                    script: 'server.js'
                }
            }
        },
        watch: {
            dev: {
                files: [ 'app/**/*' ],
                options: {
                    livereload: true
                }
            }
        }
    });
};
server.js
var express = require('express');
var app = express();
app.use(livereloadHtml(__dirname+'/../app/html'));
app.use(express.static(__dirname+'/../public'));
var port = 3000;
var host = '0.0.0.0';
app.listen(port, host, function() {
    console.log('http://' + host + ':' + port);
});

// --------------------------------

function livereloadHtml(dir) {
    var fs = require('fs');
    var lrScript = '<script type="text/javascript">document.write(\'<script src="\' + (location.protocol || \'http:\') + \'//\' + (location.hostname || \'localhost\') + \':35729/livereload.js?snipver=1" type="text/javascript"><\\/script>\')</script>';

    return function(req, res, next) {
        var path = req.url;
        if (path.charAt(path.length-1) === '/') {
            path += 'index.html';
        }

        if (path.lastIndexOf('.html') === path.length-5) {
            var fname = dir + path;
            var html = fs.readFileSync(fname, { encoding:'utf8' });
            html += lrScript;
            res.send(html);
            return;
        }

        next();
    };
}

……え、connect-livereloadなんてあるの?

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0