前言
因为在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
。