This site uses cookies to analyse traffic, remember your preferences, and optimise your experience. Learn more, read the privacy policy page.

Hexo - How to determine production mode in theme

Hexo - How to determine production mode in theme

To determine whether we are in production or development mode, we have an available variable in the template called env.
Unfortunately, the hexo documentation does not give us details of what may be there.

hexo global variables list

However, to see what is sitting there, you only need to print the contents of this variable in the template
Example themes/some-theme/layout/layout.ejs

<!DOCTYPE html>
<%= JSON.stringify(env, null, 2) %>

Then opening localhost:4000 you will see this result.

hexo env variable result

As we can see, hexo env contains an env property which represents the application mode in which it started.
In hexo server mode will be development, and when generating a static page to change the value of env.env just add NODE_ENV=production before hexo generate
NODE_ENV=production hexo generate

hexo env variable result in production mode

Now we can use the acquired variable, for example, to add analytics only in production mode.

<% if (env.env === 'production') { %>
  <!-- Global site tag (gtag.js) - Google Analytics -->
  <script async src=""></script>
    window.dataLayer = window.dataLayer || [];
    function gtag() { dataLayer.push(arguments); }
    gtag('js', new Date());

    gtag('config', 'GA_TRACKING_ID');
<% } %>

That’s all, goodbye.

Word count: 202

Want to know more and be immediately informed about new posts?

Let's stay in touch and leave your email:

Related posts: