我网站的新功能「放映厅」是基于一款名叫 hexo-bilibili-bangumi 的插件。

这款插件有个问题,就是当你本地预览时,修改了博客内容后,hexo 不能再自动地重新渲染和加载,我只能一遍又一遍用 hexo cl & hexo s 手动刷新。这曾经让我非常、非常恼火。所以我就想能不能再运行 hexo s 时不经过这个插件?

上 hexo API 文档一查,我了解到可以注册一个过滤器(Filter),在渲染页面之前,先依据修改配置文件。
它是这样描述的:

概要

1
2
3
4
5
6
7
8
9
10
hexo.extend.filter.register(type, function() {
// User configuration
const { config } = this;
if (config.external_link.enable) // do something...

// Theme configuration
const { config: themeCfg } = this.theme;
if (themeCfg.fancybox) // do something...

}, priority);

您可以指定过滤器的优先级 prioritypriority 值越低,过滤器会越早执行。 默认的 priority 是 10。 我们建议提供配置选项如 hexo.config.your_plugin.priority、让用户自行决定过滤器的优先级。
……
before_generate
在生成器解析前执行。

1
2
3
hexo.extend.filter.register("before_generate", function () {
// ...
});

因此,我们可以创建一个 before_generate 的过滤器,在渲染页面之前,先从配置文件里把插件禁用掉。

插件要求的配置,大概是长这样:

1
2
3
4
5
6
7
8
9
10
11
12
13
bangumi: # 追番设置
enable: true # 是否启用
source: bili # 数据源
path: "bangumis/bangumis.html" # 页面路径
...

cinema: # 追剧设置
enable: true # 是否启用
...

game: # 游戏设置,仅支持source: bgmv0
enable: true # 是否启用
...

所以:

1
2
3
4
5
6
7
8
9
10
11
12
13
hexo.extend.filter.register("before_generate", function () {
const isProduction = hexo.env.cmd === "generate";

hexo.config.bangumi.enable = isProduction;
hexo.config.cinema.enable = isProduction;
hexo.config.game.enable = isProduction;

if (isProduction) {
hexo.log.info("hexo-bilibili-bangumi 插件已启用(hexo generate)");
} else {
hexo.log.info("hexo-bilibili-bangumi 插件已禁用(hexo server)");
}
});

随便起个名字,你高兴就好;将这个 js 文件保存在 [BlogRoot]/scripts 下,即可。

效果如图


另外,对于这个插件,我在 [BlogRoot]/package.json 下设置:

1
2
3
4
5
6
7
8
9
10
11
12
{
"name": "hexo-site",
"version": "0.0.0",
"private": true,
"scripts": {
"build": "hexo clean && hexo bangumi -u && hexo cinema -u && hexo game -u && hexo generate && gulp",
"clean": "hexo clean",
"deploy": "hexo deploy",
"server": "hexo clean && hexo server"
},
...
}

构建命令加上插件的更新命令,就彻底解决了文章开头所说的问题。