How to add lunr.js to your site?

I think what confuses most people about this is that you need to generate a Lunr search index (which isn’t the same as the Hugo generated file) – this is some Lunr specific reverse document index. I guess you could let the client do that work, but that would be a waste.

So you need some Javascript step after the Hugo search index build, i.e. Gulp/Grunt or similar. Something ala:

	var data = {
        store: {}
    };

    var idx = lunr(function() {
        this.field('title', {
            boost: 40
        });
        this.field('keywords', {
            boost: 20
        });
  
        this.ref('href');
        
        # This is the file generated by Hugo.
        var source = JSON.parse(fs.readFileSync("public/index.json"));

        var that = this;

        source.forEach(function(item) {
            var doc = {
                'title': item.title,
                'keywords': item.keywords,
                'href': item.ref
            };

            data.store[doc.href] = item.title
            that.add(doc);
        });

    });

    data.index = idx

    var serialized = JSON.stringify(data)

    fs.writeFile('static/lunr.json', serialized, done);
2 Likes