Environments in Jekyll

Adding the ability for visitors to comment on your posts is a great way to build a community around your site and also to hear from those who may not be inclined to reach out in other ways, whether that be via email or Twitter or Facebook.

I opted to use Disqus to provide commenting functionality to my site and upon logging into the admin console recently I noticed that a number of discussions had been created with a URL beginning with http://localhost:4000/. After some investigation I discovered these were being created when I was running jekyll serve to preview my site locally and particularly when I’d added the --drafts flag to preview my draft posts. I’m not sure whether there is a downside these ‘phantom’ discussions being created but to make managing my discussions easier I wanted to prevent it happening again.

It turns out this is easy to fix by taking advantage of the different environments available in Jekyll, which are much like those in Rails (development, test & production). The default environment in Jekyll is development however you can override this by specifying an environment using the JEKYLL_ENV variable:

$ JEKYLL_ENV=production jekyll build

I already had the call to include the Disqus code wrapped in a conditional statement to only include this if I’d enabled comments for the post (by specifying comments: true in the post’s frontmatter):


{% if page.comments %}
  {% include comments_code.html %}
{% endif %}

To ensure the code was included only in live pages deployed to my server I simply wrapped this in another conditional statement as follows:


{% if jekyll.environment == "production" %}
  {% if page.comments %}
    {% include comments_code.html %}
  {% endif %}
{% endif %}

I use Google Analytics so it made sense to do the same for the tracking code to prevent my own page views in development being counted so I moved this to a partial (_includes/google_analytics.html) and wrapped the include call in the same conditional statement as above:


{% if jekyll.environment == "production" %}
  {% include google_analytics.html %}
{% endif %}

Now that the code was wrapped in the necessary conditional statements all that was left to do was to decide how to set the environment to production. Rather than having to specify this at the command line every time I built the site, I added the required code to the build task in my Rakefile:

# rake build

desc "Build the site"
task :build do
  # Set ENV to production to enable production-only code (Disqus, Google Analytics)
  execute("JEKYLL_ENV=production jekyll build")
  # Apply minification tasks
  Rake::Task[:minify_css].execute
  Rake::Task[:minify_js].execute
  Rake::Task[:minify_html].execute
end

I can now simply run:

$ jekyll build

and the environment will be set to production automatically. Your mileage will obviously vary here depending on how you’ve setup your Rakefile.