Hexo环境变量区分生产环境
source link: https://finisky.github.io/how-to-set-hexo-env/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Hexo环境变量区分生产环境
2023-01-28Hexo
最近升级NexT主题到最新版v8.14.1,相关文章功能从v8.10开始由hexo-related-popular-posts
替换成了hexo-related-posts
,后者是用tf-idf算法对文章全文进行相似度计算而得相关文章,比hexo-related-popular-posts
要精准和先进一些,不过副作用是计算量变大,在文章数较多的情况下运行会比较慢,这样在写完文章后用hexo s
进行本地调试效率就变低了,每次文章修改都要重新计算一遍tf-idf。好在
hexo-related-posts
考虑到了此问题,可以通过设置enable_env_name
变量,只在特定环境(如生产环境)中才开启此功能。不过文档略有些问题,费了一番周折才设置环境变量成功。
短答案:$ hexo <command> --<env_key> env_value
。
长答案:本文介绍了如何使用环境变量仅在生产环境开启相关文章功能。
hexo server
本地调试禁用相关文章- GitHub Action部署时开启相关文章
判断相关文章是否启用可以看hexo日志:
INFO Start processing
INFO Calculating of related posts is enabled. Start processing...
INFO TF/IDF is calculated
INFO Related post processing done
...
设置环境变量
hexo-related-posts 文档是这么写的:
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 putprod
key during running Hexo, i.e.hexo generate -- --prod
但我发现使用hexo generate -- --prod
并不能达到预期效果。看源码:
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);
即related_posts
需要enable,并在hexo.env.args
中需要存在enable_env_name
对应的值。
可惜,官方文档 #
Variables 并没有说明如何使用全局变量env
。参考了 #
Hexo Environment Variables
才知道,可以在hexo命令后加入参数即可,比如可以这样带入参数prod
,hexo.env.args
中就会存在prod
这个key:
$ hexo server --prod
$ hexo generate --prod
如果要加入value比如1也很容易:hexo server --prod 1
即可。
修改配置文件及Action Workflow
下面就需要同时修改hexo配置文件和NexT主题配置文件,对于同一插件,比较好的做法当然是在一个配置文件中管理,比如在hexo配置文件_config.yml
中加入:
related_posts:
enable: true
enable_env_name: prod
icon: fa fa-signs-post
然后将NexT主题中的相关配置还原:
related_posts:
enable: false
icon: fa fa-signs-post
测试不好使,记不太清同一变量两处设置时hexo与主题的变量优先级了,看起来主题变量的值会覆盖hexo配置。但如果仅在NexT主题配置_config.yml
中加入enable_env_name: prod
也不好使,猜想是NexT主题并没有读取此变量值。所以需要同时在hexo配置文件与NexT主题配置文件中设置enable: true
。
最后,因为使用GitHub
Action自动部署站点,需要修改下Workflow
Yaml,hexo g
时加上--prod
参数:
- name: Hexo
run: |
pandoc --version
npm i -g hexo-cli
npm i
hexo clean && hexo g --prod
由于本地调试直接使用hexo s
,所以相关文章默认会被禁用。
注意:
hexo-related-posts
有缓存功能,测试是否启用时需要修改任意一篇文章,或hexo clean
后再测试。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK