前言
因为在blog中有写关于公司的一些文章,这些东西放在blog上好像不太好,所以不想在线上可以访问到,于是萌生了在开发模式下可以看,而在线上是隐藏的想法。
思路
首先,根据Fluid主题的文档可以得知,控制文章显示的字段是hide,hide=true时,文章就不会显示在页面,但是开发模式下也无法看到,但是我在记录公司的一些工作计划以及一些自己写的文档时,我希望能打开多个页面查看,于是一个笨办法是先全局搜索hide这个字段,看它出现在了哪些地方:

可以看到,post-filter.js最符合搜索目标的要求,于是打开文件看看:
'use strict';
// 生成前过滤文章
hexo.extend.filter.register('before_generate', function () {
this._bindLocals();
const all_posts = this.locals.get('posts');
const hide_posts = all_posts.filter(post => post.hide);
const normal_posts = all_posts.filter(post => !post.hide);
this.locals.set('all_posts', all_posts);
this.locals.set('hide_posts', hide_posts);
this.locals.set('posts', normal_posts);
});
const original_post_generator = hexo.extend.generator.get('post');
hexo.extend.generator.register('post', function (locals) {
// 发送时需要把过滤的页面也加入
return original_post_generator.bind(this)({
posts: new locals.posts.constructor(
locals.posts.data.concat(locals.hide_posts.data),
),
});
});
该文件只有这几行代码,主要起作用的是:
const hide_posts = all_posts.filter(post => post.hide);
const normal_posts = all_posts.filter(post => !post.hide);
所以只要在开发模式下将hide_posts=all_posts就行了。
步骤
区分开发环境和生产环境
熟悉webpack打包的都知道,运行package.json中的脚本时,可以设置NODE_ENV,然后在运行时的代码中可以访问process.env.NODE_ENV属性。这样就有方案了。
首先在package.json中修改script属性:
"server": "set NODE_ENV=development&& hexo server"
此时npm run server运行时的process.env.NODE_ENV就是development了。
tip:注意,development和&&之间不能有空格,因为空格也会被带到变量中,对判断造成影响。
更改过滤文章的代码
const dev = process.env.NODE_ENV === 'development';
const all_posts = this.locals.get('posts');
const hide_posts = dev ? all_posts : all_posts.filter(post => post.hide);
const normal_posts = dev ? all_posts : all_posts.filter(post => !post.hide);
此时就已经能正常运行了!
其它问题
回家发现上面的代码运行不了,打断点发现NODE_ENV的值为undefined,网上一搜才发现set NODE_ENV=在windows下设置环境变量是没问题的,但是在Mac这种Linux操作系统上是无效的,解决办法是使用cross-env包来兼容种环境即可。
"server": "cross-env NODE_ENV=development hexo server"
都不用写&&符号,也不用担心空格的问题,很方便!(可以瞧瞧源码是怎么实现的)
这玩意其实hexo开发者早就想到了!
后来仔细阅读hexo的文档,发现其实只要运行hexo new draft xxxx就能生成一个草稿,草稿是不会发布的,只有运行hexo publish xxxx才会将文章从_drafts文件夹中移入_posts中去,然后发布。如果要在开发环境渲染草稿的话,需要将_config.yml文件中的render_drafts配置改为true。