Hexo Set Environment Variable

Recently I upgrade NexT theme to v8.14.1. The related post plugin hexo-related-popular-posts had been replaced by hexo-related-posts, which generates related posts by tf-idf algorithm. However, the compute cost is a little bit heavy if you have many posts. A good trade-off is enable this feature only for production environment. The plugin hexo-related-posts already takes this into account and use enable_env_name to disable its execution. Unfortunately, the document has typo so I takes some time to fix it.

So how to set environment variable in Hexo?

Short Answer$ hexo <command> --<env_key> env_value

The following secitons will illustrate how to enable related post on production.


  • Use hexo server to preview post in local, disable related post
  • Enable related post on production, deploy by GitHub Action

How to check if the related post is enabled? Just check the hexo s or hexo g log:

INFO Start processing
INFO Calculating of related posts is enabled. Start processing...
INFO TF/IDF is calculated
INFO Related post processing done

Set Environment Variable

hexo-related-posts document:

It's possible to disable plugin execution depending on env variable. For example, if you want to calculate related post only for production build, you can set this parameter to prod. In this case, related post will be generated only if you put prod key during running Hexo, i.e. hexo generate -- --prod

However, hexo generate -- --prod doesn't work. Check the source code:

const enable = (hexo.config.related_posts.enable || hexo.config.related_posts.enable === undefined) &&
(hexo.config.related_posts.enable_env_name !== undefined ? hexo.env.args[hexo.config.related_posts.enable_env_name] : true);

Hexo official document # Variables doesn't explain how to pass value to global variable env. The problem reduced to how to pass value to hexo.env.args.

Refer to this post # Hexo Environment Variables, just add parameter after hexo commands, then hexo.env.args will contains the key prod:

$ hexo server --prod
$ hexo generate --prod

If you want to pass a key/value pair, do it like this: hexo server --prod 1 .

Modify Config and GitHub Action Workflow

Modify hexo _config.yml:

  enable: true
  enable_env_name: prod
  icon: fa fa-signs-post

Modify theme NexT _config.yml

  enable: true
  icon: fa fa-signs-post

Since we # Deploy Hexo by GitHub Actions, modify the action workflow file like this (append --prod after hexo g):

- name: Hexo
  run: |
    pandoc --version
    npm i -g hexo-cli
    npm i
    hexo clean && hexo g --prod

Then related posts will be disabled by default (local hexo s).

Tips: hexo-related-posts has cache, to test if it's enabled, modify any posts or do hexo clean first.