用hexo打造非博客风的网站

hexo用来写博客很简单。hexo init my-blog
之后去这里挑个主题,改一下配置就是了。

有时候,我们想要去掉hexo自带生成的index.html而改用我们自己设计好的静态页面。
但同时,想把原来的index.html放到诸如posts/index.html的地方,这样,我们的网页就少了些许博客风,用hexo来放博客以外的东西也就更方便了。

把默认的index.html放到subdir中去

我们找不到root的index.html的模版是因为,默认的index.html是由hexo-generator-index这个插件完成的。
我们去看这个插件的内容,会发现其实非常简单,只是增加了一个生成index.html页面的扩展而已。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
hexo.extend.generator.register('index', require('./lib/generator'));


var pagination = require('hexo-pagination');

module.exports = function(locals) {
var config = this.config;
var posts = locals.posts.sort(config.index_generator.order_by);
var paginationDir = config.pagination_dir || 'page';
var path = config.index_generator.path || '';

return pagination(path, posts, {
perPage: config.index_generator.per_page,
layout: ['index', 'archive'],
format: paginationDir + '/%d/',
data: {
__index: true
}
});
};

这个插件默认会用index模版来帮我们生成顶层的index.html文件。而我们要把这个生成的index.html挪个位置,放到次级目录里面去,不需要修改插件,只需要改一下_config.yml而已。比如下面我们把这个index.html移动到posts/index.html,可以如下配置。

1
2
3
4
index_generator:
path: '/posts'
per_page: 10
order_by: -date

添加已经存在的页面到指定位置

模仿上面index.html插件的写法,我们完全可以在指定位置添加我们指定的文件。
我们新建一个scripts/myplugin.js, 添加如下内容。

1
2
3
4
5
6
7
8
9
var fs = require('hexo-fs');
hexo.extend.generator.register('statics', function(locals){
return {
path: 'index.html',
data: function(){
return fs.createReadStream(/* real static file path */)
}
}
});

real static file path 的地方放上我们实际的需要使用的静态网页就行。
这样在执行hexo g的时候,我们的页面会被复制到index.html的位置。

复制更多的静态页面

通过上面的例子,其实应该可以看出来,我们完全可以按规则复制更多的静态文件到相应的web的目录中去。
讲上例修改为下面的形式。

1
2
3
4
5
6
7
8
9
10
11
12
13
var fs = require('hexo-fs');

hexo.extend.generator.register('statics', function(locals){
let files = fs.listDirSync('statics');
return files.map(function(file){
return {
path: file,
data: function(){
return fs.createReadStream('statics/'+ file)
}
}
})
});

然后在博客目录下面建立一个statics的文件夹,里面放上我们预先设计好的静态页面就行了。

做成插件包

为了方便使用,直接做成npm的包了。直接npm install hexo-generator-statics --save 就行。
其他看ReadMe吧。

material-flow" class="codename" rel="external nofollow noopener noreferrer" target="_blank">MaterialFlow designed by Kevin Tan.