NexT 数据目录及自定义 CSS 的启用方式

Photo by Ju On on Unsplash

以前每次 Next 升级都会覆盖自定义修改,让 NexT 的升级过程非常繁琐。从 7.3 版本开始,NexT 开始采用 Hexo 的 “数据目录” 结构,将自定义内容统一挪到 source/_data,Hexo 在渲染时数据目录下文件会覆盖或插入源文件模板,于是我们可以在不改动源文件的基础上实现主题自定义,以达到平滑升级的目的。本文主要介绍

  1. 启用数据目录的方法
  2. 转移自定义文件的方法

内容更新记录

日期内容
2019-08 初稿
2020-09 兼容 NexT-8.x,调整主题配置文件位置

转移配置文件

系统环境:Hexo-4.x、NexT-7.x

hexo/source/_data 目录下新建 next.yml 文件,把 Next 的主题配置文件 next/_config.yml 内容全部复制到 next.yml,然后将 override 设置为 true

1
2
3
4
5
6
# If false, merge configs from `_data/next.yml` into default configuration (rewrite).
# If true, will fully override default configuration by options from `_data/next.yml` (override). Only for NexT settings.
# And if true, all config from default NexT `_config.yml` must be copied into `next.yml`. Use if you know what you are doing.
# Useful if you want to comment some options from NexT `_config.yml` by `next.yml` without editing default config.
- override: false
+ override: true

系统环境:Hexo-5.x、NexT-8.x

hexo/} 目录下新建 `_config.next.yml` 文件,把 Next 的主题配置文件 {% label default 内容全部复制到_config.next.yml,无需其他改动

转移之后,以后只在新位置调整主题配置。遇到 Next 版本更新时,只需把 Breaking Change 的改动同步,不需要全部重写。

启用数据目录

配置文件中有 Define custom file paths 选项,在这里选择需要自定义的文件并为其指定文件目录(建议保持默认 source/_data),以自定义样式文件为例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Define custom file paths.
# Create your custom files in site directory `source/_data` and uncomment needed files below.
custom_file_path:
#head: source/_data/head.njk
#header: source/_data/header.njk
#sidebar: source/_data/sidebar.njk
#postMeta: source/_data/post-meta.njk
#postBodyEnd: source/_data/post-body-end.njk
#footer: source/_data/footer.njk
#bodyEnd: source/_data/body-end.njk
#variable: source/_data/variables.styl
#mixin: source/_data/mixins.styl
- #style: source/_data/styles.styl
+ style: source/_data/styles.styl

启用后在 source/_data 新建 styles.styl 文件,写入 CSS 内容,即可覆盖原有样式

样式文件(styl)会覆盖旧样式,而模板文件(swig or njk)是在旧模板尾部插入内容。其实本质上都是尾部插入,只不过 CSS 在前端处理时会自动覆盖

一些其他功能

source/_data 里新建 language.yml,可以自定义翻译,格式如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
zh-CN: 
menu:
home: 首页
archives: 归档
categories: 分类
tags: 标签
about: 关于
search: 搜索
schedule: 日程表
sitemap: 站点地图
commonweal: 公益 404
tech: 技术
life: 生活
goods: 好物
reward:
donate: <i class="fa fa-qrcode fa-2x" style="line-height:38px;"></i>
wechatpay: 微信点赞
alipay: 支付宝
bitcoin: 比特币