API 手册

本文档提供了有关 API 的更详细信息,对于想要修改 Hexo 源代码或编写新插件的人尤其有用。如果你对 Hexo 的更多基本用法感兴趣,请参考 docs

¥This documentation provides more detailed information about the API and will be particularly helpful for people who want to modify the Hexo source code or write new plugins. If you are interested in more basic usage of Hexo, please refer to the docs instead.

请注意,本文档仅适用于 Hexo 3 及以上版本。

¥Please note that this documentation is only valid for Hexo 3 and above.

初始化

¥Initialize

首先,我们必须创建一个 Hexo 实例。新实例需要两个参数:网站的根目录 base_dir 以及包含初始化选项的对象。接下来,我们通过调用 init 方法来初始化此实例,然后 Hexo 会加载其配置和插件。

¥First, we have to create a Hexo instance. A new instance takes two arguments: the root directory of the website, base_dir, and an object containing the initialization options. Next, we initialize this instance by calling the init method on it, which will then cause Hexo to load its configuration and plugins.

var Hexo = require("hexo");
var hexo = new Hexo(process.cwd(), {});

hexo.init().then(function () {
// ...
});
选项 描述 默认
debug 启用调试模式。在终端中显示调试消息并将 debug.log 保存在根目录中。 false
safe 启用安全模式。不加载任何插件。 false
silent 启用静音模式。不要在终端中显示任何消息。 false
config 指定配置文件的路径。 _config.yml
draft / drafts 启用将草稿添加到帖子列表的功能。
示例:当使用 hexo.locals.get('posts')
_config.yml 的 render_drafts

加载文件

¥Load Files

Hexo 提供了两种加载文件的方法:loadwatchload 用于加载 source 文件夹中的所有文件以及主题数据。watch 执行与 load 相同的操作,但还会开始持续监视文件更改。

¥Hexo provides two methods for loading files: load and watch. load is used for loading all files in the source folder as well as the theme data. watch does the same things load does, but will also start watching for file changes continuously.

这两种方法都会加载文件列表并将它们传递给相应的处理器。处理完所有文件后,它们将调用生成器来创建路由。

¥Both methods will load the list of files and pass them to the corresponding processors. After all files have been processed, they will call upon the generators to create the routes.

hexo.load().then(function () {
// ...
});

hexo.watch().then(function () {
// You can call hexo.unwatch() later to stop watching.
});

执行命令

¥Execute Commands

可以使用 Hexo 实例上的 call 方法明确调用任何控制台命令。这样的调用需要两个参数:控制台命令的名称和一个选项参数。不同的控制台命令有不同的选项。

¥Any console command can be called explicitly using the call method on the Hexo instance. Such a call takes two arguments: the name of the console command, and an options argument. Different options are available for the different console commands.

hexo.call("generate", {}).then(function () {
// ...
});
hexo.call("list", { _: ["post"] }).then(function () {
// ...
});

退出

¥Exit

你应该在成功或不成功完成控制台命令后调用 exit 方法。这允许 Hexo 正常退出并完成重要的事情,例如保存数据库。

¥You should call the exit method upon successful or unsuccessful completion of a console command. This allows Hexo to exit gracefully and finish up important things such as saving the database.

hexo
.call("generate")
.then(function () {
return hexo.exit();
})
.catch(function (err) {
return hexo.exit(err);
});