博客搭建

摘要:本文将会全面介绍一下

1. 使用Github Pages 和 jekyll 搭建个人站点

本文将会全面介绍一下如何使用 Github Pages + jekyll 搭建个人站点,所 谓 极简 的意思就是不用使用 git 和本地构建 jekll 服务,直接在 Github 网 站上编辑设置即可,但会涉及到 jekll 的一些配置和编程控制。

参网站模板:<https://scottcgi.github.io> 使用了 github 内置的主题修改 而成。

1.1. 建立Github仓库

首先到 <https://github.com/new%3E ,创建一个仓库。仓库名称有固定的格式: username.github.io

其中 username 必须是Github账户的用户名(我的是 jaspervincent ), github.io 是固定的,这个地址将会成为个人站点的网站地址。另外,我们可以 勾选 Add a README file ,让仓库自动创建一个 README.md 文件,我们用它 来做站点的首页(当然也可以不创建,后面自行创建,或是建立index.html也行)。

注意:

  • username.github.io 是 github 默认分配给你的域名,同名仓库即代表着 默认网站内容。
  • 其他仓库就会成为 username.github.io 的子站点,比如访问地址会是: username.github.io/仓库名称

1.1.1. 设置仓库开启Github Pages

进入仓库设置界面 Settings ,如果仓库名写错,可以在这重新修改仓库名。

Settings 页面下有 Pages 的设置选项进入 Github Pages 设置页。

  • Build and deployment 有 2 种 CICD 构建方式: Deploy from a branch 从分支构建发布和 Github Actions 自动构建。 自动构建需要写固定的脚本。
  • Custom domain 设置 CNAME 信息,就可以用我们自己的域名访问了。

构建方式默认为 Deploy from a branch ,我们自定义用哪个分支构建:

  • master branch 是使用主分支也是默认的,来作为站点内容。
  • gh-pages branch 是项目新建一个分支命名为这个,使用这个分支来做站点内容。
  • master branch/docs folder 是使用主分支的docs文件夹来作为站点内容。
  • None 就是禁用Github Pages。

注意:如果是 username.github.io 只能使用主分支,其它仓库项目可以选择 其它两个。

同时官方给出来了添加 Jekyll 主题的帮助文档。

1.2. 配置 Jekyll

1.2.1. 添加 Jekyll 主题

使用要使用受“支持的主题

在仓库中创建 _config.yml 文件,添加一行信息 theme: jekyll-theme-THEME-NAME ,将 THEME-NAME 替换为主题名称,如 theme: jekyll-theme-modernist

到这里网站就最简单的设置完成了,接下来只需要把 markdown 文件和 html 文 件放入仓库就可以展示了。比如在 jekyll-website 仓库中新建 REAMDE.md 文件

# Jekyll-website
List
- [Blog](https://jaspervincent.github.io)

访问 https://jaspervincent.github.io/jekyll-website 查看效果

另外,更多主题可以参看这两个地址:

如果想自定义,可以把官方主题仓库拷贝过来,从默认配置文件修改。

1.2.2. jekyll的目录结构

我们只需要关注几个核心的目录结构如下(可以自己创建):

  • _config.yml 全局配置文件
  • _layouts 存放页面模板,md或html文件的内容会填充模板
  • _includes 可以复用在其它页面被 include 的 html 页面
  • _posts 博客文章页面 有 index ,默认启用 README.md 文件
  • _sass 存放样式表
  • assets 原生的资源文件
    • js
    • css
    • image
  • index.html, index.md, README.md 首页 index.html 优先级最高,如果没
  • 自定义文件和目录

更多更详细的目录结构参看jekyll官网:https://jekyllrb.com/docs/structure

1.2.3. jekyll的模板编程语言Liquid的使用

  • 变量 {{ variable }} 被嵌入在页面中,会在静态页面生成的时候被替换成 具体的数值。常用的全局变量对象有: sitepage 。这两个对象有很 多默认自带的属性,比如: {{ site.time }}{ page.url }} 。更多 的默认值参看: <https://jekyllrb.com/docs/variables>。
  • site 对象对应的就是网站范围,自定义变量放在 _config.yml 中,比如 title:标题 使用 { site.title }} 访问。
  • page 对象对应的是单个页面,自定义变量放在每个页面的最开头,比如:

    ---
     myNum:100
     myStr:我是字符串
    ---
    

    使用 {{ page.myNum }}{{ page.myStr }} 访问。

    如定义默认 page 变量

    ---
    layout: post
    title: 5年
    categories: [Business, Linux]
    ---
    
  • 条件判断语句,更多详见:https://shopify.github.io/liquid/tags/control-flow

    {% if site.title == 'Awesome Shoes' %}
      These shoes are awesome!
    {% endif %}
    
    {% if site.name == 'kevin' %}
      Hey Kevin!
    {% elsif site.name == 'anonymous' %}
      Hey Anonymous!
    {% else %}
      Hi Stranger!
    {% endif %}
    
  • 循环迭代,更多详见:https://shopify.github.io/liquid/tags/iteration

    {% for product in collection.products %}
      {{ product.title }}
    {% endfor %}
    
  • 默认函数,可以对变量进行一些处理,比如大小写转化、数学运算、格式化、 排序等等,在 Liquid 中叫做 Filters。比如 {{ "Hello World!" | downca se }} 转换字符串为小写。更多内置函数详见:https://jekyllrb.com/docs/liquid/filters

    // 定义 count 变量,计算所有文章字数
    {% assign count = 0 %}
    {% for post in site.posts %}
    {% assign single_count = post.content | strip_html | strip_newlines | remove: " " | size %}
    {% assign count = count | plus: single_count %}
    {% endfor %}
    
    {{ site.posts.size }}篇文章
    {{ count }}字
    
    // 输出日期,需要文件按指定方式命名 YEAR-MONTH-DAY-title.MARKUP
    // 2011-12-31-new-years-eve-is-awesome.md
    // https://jekyllrb.com/docs/posts/
    {{ post.date | date: "%Y-%m-%d" }}
    

1.2.4. 使用 _config.yml 文件设置 jekyll

我们就可以配置一些默认的属性来控制 jekyll 的编译过程。 更多详细的内置属性详见:https://jekyllrb.com/docs/configuration/default

同时我们可以自定变量,会自动绑定到 site 对象上,比如我们可以把导航配 置到 _config.yml 中:

默认站点访问 / 就可以,如果是子站点,需要仓库名加上 如 /jekyll-website。

  • 网站地址变量: site.url 即主站 https 地址
  • 网站基本路径变量为: site.baseurl 主站仓库变量值为 / ,子站变量值为 /仓库名
  • page.url 值为 文件名.html
title      : jasperVincent的项目列表
lang       : zh
description: 编程写作
copyright  : © 2021 jasperVincent All Rights Reserved
theme: jekyll-theme-modernist

nav:
 - name: 中文
   link: /jekyll-website
 - name: 捐赠
   link: /jekyll-website/donations/
 - name: En
   link: /jekyll-website/about/

调用变量,使用 markdown 文件或者 html 文件都可以,如 REAME.md 添加内容:

# Jekyll-website
List
- [Blog](https://jaspervincent.github.io)
- [jekyll-website](https://jaspervincent.github.io/jekyll-website)
- [hugo-website](https://jaspervincent.github.io/hugo-website)

- [jekyll-归档]({{ site.url }}{{ site.baseurl }}/archive.html)
- [hugo-归档](https://jaspervincent.github.io/hugo-website/tags/)

<nav>
  site.url: {{ site.url }}<br>
  site.baseurl: {{ site.baseurl }}<br>
  page.url: {{ page.url }} <br>

  {% assign baseurl = "/jekyll-website" | join: page.url %}
  baseurl: {{ baseurl }}<br>

  {% for item in site.nav %}
    <a href="{{ item.link }}" 
      {% if  baseurl == item.link %} style="color: red;" {% endif %}
    >
      {{ item.name }} -- 
    </a>
  {% endfor %}
</nav>

等构建完成访问看看效果。

当然,我们也可以把一些数据单独放入一个 yml 文件,然后放在固定的数据 文件夹 _data 下,比如 _data/navigation.yml ,这样访问这个文件的数 据对象就是 site.data.navigation

1.2.5. _layouts模板配置

_layouts 文件夹存放的是页面模板,默认需要一个 default.html , 就是 说,layout 提供一个页面的布局框架,这是固定的模式,包括样式、结构、布 局、脚本控制等等。然后,我们在用其它 md 或 html 文件去动态填充这个框架, 这样就形成了一个完整的页面。

比如从官方主题仓库中 default.html 内容复制,在自己仓库中创建 _layou ts/default.html 修改一下:

<!doctype html>
<html lang="{{ page.lang | default: site.lang }}">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">

    {% seo %}

    <link rel="icon" href="https://avatars0.githubusercontent.com/u/1797320" type="image/x-icon" title="scottcgi">
    <link rel="stylesheet" href="{{ 'https://scottcgi.github.io/assets/css/style.css?v=' | append: site.github.build_revision | relative_url }}">

    <script src="{{ '/assets/js/scale.fix.js' | relative_url }}"></script>
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">

  </head>
  <body>
    <div class="wrapper">
      <header {% unless site.description or site.github.project_tagline %} class="without-description" {% endunless %}>
        <h1>{{ site.title | default: site.github.repository_name }}</h1> 
        <p>{{ page.description | default: site.description }}</p>
        {% assign baseurl =  site.baseurl | join: page.url %}

        <ul>
        {% for item in site.nav %}
          {% if baseurl == item.link %}
            <li style="background-color:#069">
              <a href="{{ item.link }}">
                <strong>{{ item.name }}</strong>
              </a>
            </li>
          {% else %}
            <li><a href="{{ item.link }}">{{ item.name }}</a></li>
          {% endif %}
        {% endfor %}
            <li><a href="{{ site.baseurl }}/feed.xml">Feed RSS</a></li>
            <li><a href="{{ site.github.repository_url }}">View On <strong>GitHub</strong></a></li>
        </ul>
      </header>
      <section>

      {{ content }}

      </section>
    </div>

    <footer>
      <p>{{ site.copyright | default: "copyright not found in _config.yml" }}</p>
    </footer>
  </body>
</html>
  • {% seo %} 是jekyll的一个插件提供的seo优化, 详情在这里:https://github.com/jekyll/jekyll-seo-tag
  • 核心在于 {{ content }} 这个变量是内置的,会用我们的md或html页面填 充这部分内容。
  • 其它的,我们看到会大量使用变量和流程控制代码,来填充模板的方方面面。
  • 于是,填充模板的内容,一方面是来自读取配置文件的变量,一方面是来自 _includes 的页面,还有就是来自 {{ content }} 对应的页面。

当然,我们也可以不使用 {{ content }} 来填充模板,而是使用 _includes 的页面来代替 {{ content }} ,但这样不够灵活,因为使用 {{ content }} , 我们可以在每个页面单独设置对应的 layout 模板。

1.2.6. md 和 html 页面编写

站点内容页面,可以使用 markdown 或 html 来编写,但 markdown 编写的 md 文件,在浏览器地址访问的时候依然使用html文件后缀。推荐使用 markdown 来 书写内容,语法参见:Github md 示例Github md教程。比如下面这个

about.md 页面:

---
layout: default
title: About
description: linux Engine Developer
permalink: /about/
lang: en
---
# About page

This page tells you a little bit about me.
  • layout: default 告诉jekyll这个页面使用哪个模板,即这个页面会放入哪 个模板的 {{ content }} 。当然,我们可以在 _layouts 文件夹下提供 多个不同的模板,然后根据需要不同的页面使用不同的 layout
  • permalink 固定连接 页面可以放在任意位置和目录,访问的时候从站点域 名开始,带上目录名称,再次注意需要使用 html 结尾。如果想要自定义浏览 器的访问路径,可以参看详细设置:permalinks

1.2.7. 博客文章编写和管理

我们自然可以新建目录,提交文章,然后添加一个文章列表页面。但我们也可以 把这些交给jekyll的内置机制来完成,因为它提供了一些方便的内置文章管理功能。

  • _posts 文件夹是内置的放置文章的目录,我们可以将固定格式 year-moth-day-name.md 名称的 md 文件放到这里。

    比如 _posts/2011-12-31-new-years.md

    ---
    layout: post
    title: New
    categories: [Think]
    ---
    
    这是一篇博客文章。
    
  • 接下来我们需要添加 post 的模板, _layouts/post.html

    <!DOCTYPE html>
    
    <html>
        <!--
        <head>
            % include header.html %
    
            <link rel="stylesheet" href="{{site.url}}/styles/font.css">
            <link rel="stylesheet" media="screen and (min-width: 600px)" href="{{site.url}}/styles/post.css">
            <link rel="stylesheet" media="screen and (max-width: 600px)" href="{{site.url}}/styles/post_mobile.css">
            <link rel="stylesheet" media="screen and (min-width: 600px)" href="{{site.url}}/styles/navigatebar.css">
            <link rel="stylesheet" media="screen and (max-width: 600px)" href="{{site.url}}/styles/navigatebar_mobile.css">
            <link rel="stylesheet" href="{{site.url}}/theme/highlight.css">
        </head>
    -->
        <body>
            <!-- % include navigatebar.html % -->
    
            <div class="site-masthead">
              <div class="container">
                <nav class="nav">
                  <a class="nav-link" href="{{ site.url }}{{site.baseurl}}/index.html">Home</a>
                  <a class="nav-link" href="{{ site.url }}{{site.baseurl}}/tags.html">Tags</a>
                  <a class="nav-link" href="{{ site.url }}{{site.baseurl}}/about/">About</a>
                  <a class="nav-link" href="{{ site.url }}{{site.baseurl}}/feed.xml">Feeds RSS</a>
                </nav>
              </div>
            </div>
    
            <div class="slogan">
              「生活可以更简单, 欢迎来到我的开源世界」
            </div>
    
            <div class="content-area">
                <div class="title">
                    {{ page.title }}
                </div>
                <div class="category-area">
                    「{% for category in page.categories %}
                    <a href="{{ site.url }}{{ site.baseurl }}/tags.html#{{ category }}">
                        <div class="category">
                            {{ category }}
                        </div>
                    </a>
                    {% endfor %}」
                </div>
                <div class="char-counter">
                  {{ page.date | date: "%Y-%m-%d" }} {{ page.content | strip_html | strip_newlines | remove: " " | size }}字
                </div>
                <div class="content">
                    {{ content }}
                </div>
            </div>
        </body>
    </html>
    
  • 最后,我们还需要编写一个博客文章列表的页面,用来展示所有的文章。比如 在根目录新建 archive.html 页面:

    ---
    layout: default
    title: Blog
    ---
    
    <h1>Latest Posts</h1>
    
    <ul>
    {% for post in site.posts %}
      <li>
        <h2><a href="{{ site.baseurl }}{{ post.url }}">{{ post.title }}</a></h2>
        <p>{{ post.excerpt }}</p>
      </li>
    {% endfor %}
    </ul>
    
    #------------------
    
    <ul>
      <div class="char-total-counter" style="display: flex;justify-content: flex-end;margin-right: 20px;">
        {% assign count = 0 %}
        {% for post in site.posts %}
        {% assign single_count = post.content | strip_html | strip_newlines | remove: " " | size %}
        {% assign count = count | plus: single_count %}
        {% endfor %}
    
        {{ site.posts.size }}篇文章
        {{ count }}字
      </div>
    
      {% for post in site.posts %}
    
      <li class="post-line">
        <a
          class="post-title"
          href="{{ site.baseurl }}{{ post.url }}">
          {{ post.title }}
        </a>
    
        <a href="{{ site.baseurl }}{{ post.url }}">
          <div class="post-summary">
            {{ post.content | strip_html | truncate: 80, " ..." }}
          </div>
        </a>
        <div class="post-info" style="display: flex;justify-content: space-between;">
          <div class="category-area">
            {% for category in post.categories %}
            <a href="{{ site.url }}{{ site.baseurl }}/tags.html#{{ category }}">
              <div class="category">
                {{ category }}
              </div>
            </a>
            {% endfor %}
          </div>
          <div class="right-info-area" style="display: flex;">
            <div class="char-counter">
              {{ post.content | strip_html | strip_newlines | remove: " " | size }}字
            </div>
    
            <div class="post-date">
              {{ post.date | date: "%Y-%m-%d" }}
            </div>
          </div>
        </div>
      </li>
    
      {% endfor %}
    
    </ul>
    
    • site.posts jekyll会自动生成=_posts=目录的对象。
    • post.url jekyll会自动会设置在=_posts=目录下的页面url。
    • post.title 默认是md文件名称,但也可以在文章页面自定义 title: 我的文章自定义名称
    • post.excerpt 默认是文章第一段的摘要文字。
  • 文章连接地址格式化 permalink

    默认的 post.urlpermalink: /:categories/:year/:month/:day/:title:output_ext

    _config.yml 中添加:

    collections:
      posts:
        permalink: /:year/:month/:day/:title/
    

    更多官方文档: https://jekyllrb.com/docs/permalinks/#global

  • 订阅插件

    _config.yml 中添加:

    plugins:
      - jekyll-feed
    

    在网站网站下生成 feed.xml 文件

1.3. Github Pages的限制

Github Pages 并不是无限存储和无限流量的静态站点服务,一些限制如下:

  • 内容存储不能超过1GB。
  • 每个月100GB流量带宽。
  • 每小时编译构建次数不超过10次。(在线修改重新编译并未发现这个限制)
  • 更多参看官方说明:usage-limits

1.4. 范例

index.md文件内容

- [jasperVincent博客](http://xuchangwei.com)
- [文档](https://jaspervincent.github.io/pic)
- [个人介绍](https://me.xuchangwei.com)

访问网站https://jaspervincent.github.io/

pages/donations.md文件内容

---
description: 万物皆比特,一切可编码,宇宙是计算。
title: 捐赠
permalink: /donations/
---
如果您觉得本博客的原创博文或我维护的开源项目对您有用,可以考虑通过捐赠来支持本博客。

#### 免责声明
1. 本博客致力于知识和技术分享,不以盈利为目的,是个人维护的独立博客;
2. 本人不对本博客的更新和维护周期做任何承诺;
3. 捐赠者的捐赠行为完全自愿,本人与各捐赠者之间不构成购买或雇佣关系;
4. 收到的捐赠款项由本人完全支配,本人没有义务对款项的用途做解释;
5. 除非特别注明,本人会在该页面列出捐赠者的姓名、捐赠日期以及捐赠金额,并承诺不向任何组织或个人透漏其他身份信息;

#### 捐赠方式
对于无独立经济来源的学生而言,不推荐进行大额捐赠。
webchat-ali-pay.jpg
Figure 1: webchat-ali-pay
注意事项:

1. 请尽量留言以表明自己是为seisman博客捐赠,以免与我的其它交易混淆;
2. 偶尔交易提醒会忘记加入到以下列表中。如有遗漏,可以给 seisman.info@gmail 发邮件告知。
3. 微信支付不再提供支付者信息,故而姓名处只能填写“微信用户”。如果你想列出自己的名字, 请在转账时填写备注或邮件告知。

#### 捐赠名单
本博客自开通捐赠以来收到的捐赠款项在下表列出。捐赠者信息由支付宝或微信提供,若您不希望列出自己的姓名, 请在捐赠时说明或在捐赠后邮件联系。

合计

2021年: 0元

Jekyll 网站博客

2. 使用 hugo 搭建个人站点

2.1. 安装 Hugo

如果你是 Windows 用户:

下载地址:https://github.com/gohugoio/hugo/releases

如果你是 Mac 用户:

brew install hugo

安装完后自行配置环境变量,引用hugo命令

查看hugo版本 hugo version

2.2. 创建一个新的网站

在工作目录中打开命令行终端,如 windos cmd。

输入命令: hugo new site blog

$ hugo new site blog
Congratulations! Your new Hugo site was created in D:\github\tmp\blog.

Just a few more steps...

1. Change the current directory to D:\github\tmp\blog.
2. Create or install a theme:
   - Create a new theme with the command "hugo new theme <THEMENAME>"
   - Install a theme from https://themes.gohugo.io/
3. Edit hugo.toml, setting the "theme" property to the theme name.
4. Create new content with the command "hugo new content <SECTIONNAME>\<FILENAME>.<FORMAT>".
5. Start the embedded web server with the command "hugo server --buildDrafts".

See documentation at https://gohugo.io/.

以上命令行会创建一个新的文件夹 blog,该文件夹下包含 Hugo 最基本目录结 构,其中blog_test目录下文件如下:

.
├── archetypes/
│   └── default.md
├── assets/
├── content/
├── data/
├── i18n/
├── layouts/
├── static/
├── themes/
└── hugo.toml         <-- site configuration

根据要求,您可能希望将站点配置组织到子目录中:

├── archetypes/
│   └── default.md
├── assets/
├── config/           <-- site configuration
│   └── _default/
│       └── hugo.toml
├── content/
├── data/
├── i18n/
├── layouts/
├── static/
└── themes/

生成文件包含几个文件夹 和 1个全局配置文件,下面依次对这7个文件做相应的说明。

archetypes/ 目录

新建文章时默认模板,当使用 hugo new 新建文章 时会生成默认模板格式的文 件,该文件夹配置的优先级高于文件夹 theme/ 下相应主题的 /archetypes 设置。一般情况下,/archetypes 下仅包含default.md文件,内容为:

---
title: "{{ replace .Name "-" " " | title }}"
date: {{ .Date }}
draft: true
---

当使用 hugo new 新建文章 时,文章头部默认会有以上这段内容。其中包含 标题(根据文件名推断而来)、日期及draft属性,一般我们会把draft属性去 掉( draft: true ),draft是草稿的意思,一般有这个属性的md文件不会生成 显示,若不删除,则在生成网页时需通过 hugo -D 强制显示。或者我们还 可以直接使用主题里帮我们设置好了的 /archetypes 配置

hugo.toml 文件
该文件为站点全局配置文件。该文件 非常重要 ,直接决定网站最终的显示 元素和布局。同时 hugo.yaml、hugo.json 格式
config 目录
该 config 目录包含站点配置,可能拆分为多个子目录和文件。对于配置最少 的项目或不需要在不同环境中表现不同的项目,在项目根目录中命名 hugo.to ml 的单个配置文件就足够了。查看详细资料
content/ 目录
存放个人blog内容的目录,即我们所有写的文章都应存放在content目录下, 也是Hugo默认的内容目录,类似于hexo的source 。我们应该重点组织好conte nt目录内的内容,后期在切换网页框架时(因为Web的开源框架也在日益升级 迭代),也只需迁移content目录里的内容即可。
data/ 目录
存储Hugo框架在生成网页时使用到的配置文件,类似于hexo的source/_data , 该文件夹默认为空。最好不要自己手动设置这个目录的配置,保持默认为空或 者使用主题里设置好了的配置。
layouts/ 目录
存储 .html 网页内容的生成模板,该文件夹的优先级高于文件夹 theme/ 下 相应主题下的 /layouts ,该文件夹默认为空。一般不从事Web前端的开发, 对于新手来说自己组织有点困难,通常保持该文件夹为空或者使用主题里设置 好了的配置。
static/ 目录
存储 images、CSS和JS等静态文件,当使用Hugo创建生成网页时,该目录下的 文件会直接copy到 public 目录下。该文件夹的优先级高于文件夹 theme 下相应主题下的 /static 文件夹,该文件夹默认为空。一般不从事Web前端的 开发,对于新手来写CSS和JS脚本会有点困难,我这里是直接应用主题里自带 的 /static 。
themes/ 目录
存放网站主题的目录,themes目录下的每个子目录代表一个主题,可以在 config.toml中通过参数theme指定主题(主题即theme目录下的子目录的名字)。

更多细节: https://gohugo.io/getting-started/directory-structure/

2.3. 添加主题和生成站点

官方主题 https://themes.gohugo.io/ 。这是使用主题 hugo-xmin

XMin 主题总共包含大约 130 行代码,包括 HTML 模板和 CSS 中的代码(也计算空行)。

主要关注 3 个文件,即 config.toml、content/ 和 themes/ 。其余文件夹(a rchetypes/、 data/ 、layouts/ 和 static/ )在默认生成的情况下都为空文 件夹,这些影响布局的属性主要依赖主题文件夹(即 themes/ )对应主题的相 应的配置值,下面主要介绍配置主题和生成博客的过程。

下载主题

# 安装主题到blog目录里的themes文件夹
cd blog
git clone https://github.com/yihui/hugo-xmin.git themes/hugo-xmin
#git clone https://github.com/flysnow-org/maupassant-hugo themes/maupassant
#git submodule add https://github.com/budparr/gohugo-theme-ananke.git themes/ananke

# 删除默认配置
rm -f hugo.toml

默认样式是没有的,直接把themes/hugo-xmin/exampleSite下的文件覆盖到blog 目录下,将 config.yaml 重命名为 hugo.yaml。

hugo.yaml 文件配置

# 网站的根URL,需修改成自己的
baseurl: "/" #方便本地调试
#baseurl: "https://jaspervincent.github.io/hugo-website"
# 网站默认的语言,我一般是默认值
languageCode: "en-us"
# 首页的标题,需修改成自己的
title: "hugo-website"

# 这里是使用的主题是hugo-xmin,网页的布局将使用对应主题的archetypes、layouts和static配置
theme: "hugo-xmin"

params:
  footer: "&copy; [Jasper Hsu](https://jaspervincent.github.io/hugo-website) 2023 -- {Year} | 
  [Github](https://github.com/jaspervincent) | [RSS](https://jaspervincent.github.io/hugo-website/index.xml) |
  [CC-BY-NC-ND 4.0](https://creativecommons.org/licenses/by-nc-nd/4.0/)"

# 板块化分,weight对应在页面上显示的次序。
#menu

添加文章

# 添加文章,会在content目录下创建posts/my-first-post.md
cd blog
hugo new post/my-first-post.md
hugo new post/second.md

文章内容

---
title: "Test"
date: 2021-01-28T03:29:09+08:00
draft: false # 这里是否为草稿,否
tags: ["test"]
categories: ["test"]
url: "/2019/12/18/test.html"
---

### hello world

second.md

---
title: Second page
author: Jasper Hsu
date: '1999-06-13'
tags: ["Test"]
categories:
  - Test
slug: a-quick-note
---

## Second

本地测试

# windows
hugo server -D
# 启动本地服务,根据显示浏览器访问http://localhost:1313/

# linux
hugo server --bind="0.0.0.0" -v -w -p 8080 -b http://xuchangwei.com

2.4. github创建github page

创建仓库

最好仓库名为账号名+github.io形式,这是为 https://github.com/jaspervincent/hugo-website

初始化hugo

可以用git命令克隆下来,我这里使用github desktop克隆代码,并用vs打开本地目录

hugo --theme=hugo-xmin # blog目录下生产public文件夹

上传到github 仓库

#  hugo.yaml 文件,找到 baseurl,填入github仓库地址
baseurl: "https://jaspervincent.github.io/hugo-website"

# 打包网站到/docs目录,以后有新文章,每次都要打包一下
#hugo -d docs
#第一次发布网站时,仓库中选设置"setting",将github page 生效路径指定为/docs

# 上传github
cd public
git init
git add .
git commit -m "first commit"
git remote add origin [email protected]:jaspervincent/hugo-website.git

git push -u origin master

第一次发布网站时,仓库中选设置”setting”,将github page 生效路径指定为/

现在访问看看效果,https://jaspervincent.github.io/hugo-website/

到此,建站完成。

参考:

2.4.1. Docsy Hugo 主题

准备

hugo version #请检查您的版本,会看到 Extende
go version # 1.12 或者更高版本
  • 安装 PostCSS ,以便网站构建可以创建最终的 CSS 资产。您可以通过从项目的根目录运行以下命令在本地安装它

    npm install --save-dev autoprefixer
    npm install --save-dev postcss-cli
    
    #从版本 8 开始 postcss-cli ,您还必须单独安装 postcss :
    npm install -D postcss
    

示例

git clone --depth 1 --branch v0.9.1 https://github.com/google/docsy-example.git my-new-site
cd  my-new-site
hugo server

浏览器访问http://localhost:1313

参考网站:

3. Gitbook

gitbook 是一个基于 Node.js 的命令行工具

安装 node.js

下载地址: https://nodejs.org/en/ 找到对应平台的版本安装即可

node.js 换成 v12 版本

# 配置环境变量
echo 'export PATH=$PATH:/usr/local/node/bin' >> ~/.bash_profile
source ~/.bash_profile

# 验证 node 版本
node -v

# 官方源下载太慢,切换为国内源
npm install -g cnpm --registry=https://registry.npm.taobao.org
# npm换源
npm config set registry=http://registry.npm.taobao.org -g

3.1. 安装 gitbook-cli

Node.js 都会默认安装 npm (node包管理工具),执行以下命令安装 GitBook:

npm install -g gitbook-cli

查看 cli 版本信息

gitbook --version

报错修改

C:\Users\jasper\AppData\Roaming\npm\node_modules\gitbook-cli\[email protected]@npm\node_modules\graceful-fs\polyfills.js
// fs.stat = statFix(fs.stat) // fs.fstat = statFix(fs.fstat) //
fs.lstat = statFix(fs.lstat)

也可以手动指定gitbook安装版本

gitbook ls-remote # 查看所有版本信息 gitbook fetch 3.2.3 # 指定版本安装

3.2. 制作电子书

# 初始化目录
mkdir ebook
cd ebook
gitbook init # 文件夹里会多两个文件 
#README.md(书籍的介绍在这个文件里)
#SUMMARY.md(书籍的目录结构在这里配置)

编辑md文件,向文件添加内容

语法:中括号里是这个目录的名字,小括号里是路径。

# Summary

* [Introduction](README.md)
* [前言](readme.md)
* [第一章](part1/README.md)
    * [第一节](part1/1.md)
    * [第二节](part1/2.md)
    * [第三节](part1/3.md)
    * [第四节](part1/4.md)
* [第二章](part2/README.md)
* [第三章](part3/README.md)
* [第四章](part4/README.md)

写完目录后再次执行 gitbook init ,Gitbook 会查找 SUMMARY.md 中描述的 目录和文件,如果没有则会创建。

运行gitbook 预览这本书:

gitbook serve
Live reload server started on port: 35729
... ... 
Serving book on http://localhost:4000  
# 默认监听在本地4000端口,可以进行访问和测试

生成电子书

导出电子书,需要用到calibre插件,下载地址:https://calibre-ebook.com/download

构建静态web页面
gitbook build

# 安装calibre插件
# linux
sudo -v && wget -nv -O- https://download.calibre-ebook.com/linux-installer.sh | sudo sh /dev/stdin
# 首先打开你笔记文件夹下的book.json文件,没有就自己创建一个
#将以下代码复制进去
{
  "plugins": ["summary"]
}
gitbook install

# 导出电子书
gitbook pdf  # 生成pdf格式电子书
gitbook modi # 生成mobi格式电子书
gitbook epub # 生成epub格式电子书

插件使用

gitbook的插件大部分都在 npm 上,可以访问 npm 官网查看搜索插件https://www.npmjs.com/

首先打开你笔记文件夹下的book.json文件

book.json 是 gitbook 的配置文件,包括插件的配置文件,通过插件可以丰富电子书的功能

1, “title”: “前端家族集锦”,
2, “description”: “重学前端,梳理自己的前端格局”,
3, “author”: “贰拾壹先生”,
4, “language”: “zh-hans”, // 简体中文
5, 插件列表

theme-default 插件地址: https://plugins.gitbook.com/plugin/theme-default

theme-default 是 3.0.0。引入的默认主题,大多数插件针对的都是默认主题,如 果切换到其他主题或者自定义主题,可能会造成某些情况下不兼容,甚至报错

范例:

"pluginsConfig": {
    "theme-default": {
        "showLevel": true
    }
}

gitbook-plugin-icp 用于在首页页脚区域添加 icp 网站备案信息的 Gitbook 插件

  1. pluginsConfig ,将 number 值设置为您自己的 icp 网站备案编号.
  2. pluginsConfig , labellink 值是可选的,默认情况下,链接地址为 http://www.beian.miit.gov.cn/ .
{
    "plugins": ["icp"],
    "pluginsConfig": {
        "icp": {
            "number": "浙ICP备18042346号"
        }
    }
}
{
    "plugins": ["icp"],
    "pluginsConfig": {
        "icp": {
            "label": "YOUR OWN ICP LABEL",
            "number": "YOUR OWN ICP NUMBER",
            "link":"YOUR OWN ICP LINK"
        }
    }
}

范例

"plugins": [
  "-lunr", "-search", "search-pro", // 删除默认搜索功能,添加中文高级搜索
  "back-to-top-button", // 回到顶部
  "chapter-fold", // 导航目录折叠
  "expandable-chapters-small", // 左侧章节目录可折叠
  "code", // 代码添加行号
  "copy-code-button", // 代码添加复制按钮
  "advanced-emoji",
  "splitter", // 侧边栏宽度可调节
  "-sharing", "sharing-plus", // 增加分享功能
  "tbfed-pagefooter", // 添加底部页脚
  "adsense", // 广告
  "donate" // 打赏功能
 ],
# gitbook-plugin-back-to-top-button 回到顶部
npm install gitbook-plugin-back-to-top-button

# gitbook-plugin-chapter-fold 导航目录折叠
npm install gitbook-plugin-chapter-fold

# expandable-chapters-small 左侧章节目录可折叠
npm install gitbook-plugin-expandable-chapters-small

# gitbook-plugin-code 代码添加行号
npm install gitbook-plugin-code
"pluginsConfig": {
        "code": {
        "copyButtons": false
    }
  }

# gitbook-plugin-copy-code-button 代码块复制按钮
npm install gitbook-plugin-copy-code-button

# gitbook-plugin-search-pro 高级搜索,支持中文
npm install gitbook-plugin-search-pro

#gitbook-plugin-advanced-emoji 支持emoji表情
npm install gitbook-plugin-advanced-emoji

# gitbook-plugin-github 右上角添加github图标
npm install gitbook-plugin-github
"pluginsConfig": {
      "github": {
          "url": "https://github.com/zhangjikai"
      }
  }

# gitbook-plugin-splitter 侧边栏宽度可调节
npm install gitbook-plugin-splitter

# gitbook-plugin-sharing-plus 分享,比默认的分享功能多
npm install gitbook-plugin-sharing-plus

# gitbook-plugin-tbfed-pagefooter 页脚,版权信息
npm install gitbook-plugin-tbfed-pagefooter

# npm install gitbook-plugin-donate 打赏插件
npm install gitbook-plugin-donate

# npm install gitbook-plugin-change_girls 可自动切换的背景
npm install gitbook-plugin-change_girls
# book.json
{
    "title": "learn 学习 by Jasper Hsu(徐长伟)",
    "description": "learn 学习 by Jasper Hsu(徐长伟)",
    "author": "Jasper Hsu(徐长伟)",
    "language": "zh-hans", 
    "link": {
        "sidebar": {
            "HOME": "https://www.baidu.com"
        }
    },
    "plugins": [
        "-lunr", "-search", "search-pro",
        "back-to-top-button",
        "chapter-fold",
        "expandable-chapters-small",
        "code",
        "copy-code-button",
        "advanced-emoji",
        "splitter",
        "-sharing", "sharing-plus",
        "tbfed-pagefooter",
        "favicon@^0.0.2",
        "donate"
    ],
    "pluginsConfig": {
        "code": {
            "copyButtons": true
        },
        "github": {
            "url": "https://github.com/zhengliming"
        },
        "tbfed-pagefooter": {
            "copyright":"<p><a href=https://xuchangwei.com>徐长伟的个人博客</a> | <a href=https://www.cncf.io/>加入云原生社区</a></p>Copyright © 2021 | Distributed under <a href=https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh>CC BY 4.0</a> | <a href=https://xuhcangwei.com>xuchangwei.com</a>"",
            "modify_label": "Updated at ",
            "modify_format": "YYYY-MM-DD HH:mm:ss"
        },
        "favicon": {
            "shortcut": "favicon.ico",
            "bookmark": "favicon.ico"
        },
        "donate": {
            "wechat": "./images/11.jpg",
            "alipay": "./images/22.jpg",
            "title": "",
            "button": "",
            "alipayText": "支付宝打赏",
            "wechatText": "微信打赏"
        },
        "change_girls" : {
            "time" : 10,
            "urls" : [
                "girlUrl1", "girlUrl2"
            ]
        },
        "sharing": {
            "douban": false,
            "facebook": false,
            "google": true,
            "hatenaBookmark": false,
            "instapaper": false,
            "line": true,
            "linkedin": true,
            "messenger": false,
            "pocket": false,
            "qq": false,
            "qzone": true,
            "stumbleupon": false,
            "twitter": false,
            "viber": false,
            "vk": false,
            "weibo": true,
            "whatsapp": false,
            "all": [
                "douban", "facebook", "google", "hatenaBookmark", 
                "instapaper", "linkedin","twitter", "weibo", 
                "messenger","qq", "qzone","viber","vk","weibo",
                "pocket", "stumbleupon","whatsapp"
            ]
        }
    }
}

参考:

4. 使用 Zola 搭建个人站点

Rust web 开发框架,静态网站生成器,类似于 Hugo、Pelican 和 Jekyll。 高度兼容的 Markdown 规范。

官方: https://www.getzola.org/

CentOS

# install
sudo yum install epel-release
sudo yum install snapd
sudo systemctl enable --now snapd.socket
sudo ln -s /var/lib/snapd/snap /snap
sudo snap install zola --edge
# env
echo 'PATH=/var/lib/snapd/snap/bin:$PATH' >> /etc/profile
source /etc/profile
# check
# zola --version
zola 0.18.0

使用

# zola init myblog
Welcome to Zola!
Please answer a few questions to get started quickly.
Any choices made can be changed by modifying the `config.toml` file later.
> What is the URL of your site? (https://example.com): 
> Do you want to enable Sass compilation? [Y/n]:      
> Do you want to enable syntax highlighting? [y/N]: 
> Do you want to build a search index of the content? [y/N]: 

# tree myblog/
myblog/
├── config.toml
├── content
├── sass
├── static
├── templates
└── themes

# cd myblog/
# zola  serve -i 0.0.0.0
Web server is available at http://0.0.0.0:1111

主题: https://www.getzola.org/themes/

abridge 主题: https://www.getzola.org/themes/abridge/

# Install Abridge
git clone https://github.com/jieiku/abridge.git themes/abridge

# Configuration
rsync themes/abridge/.gitignore .gitignore
rsync themes/abridge/config.toml config.toml
rsync themes/abridge/content/_index.md content/
rsync -r themes/abridge/COPY-TO-ROOT-SASS/* sass/
rsync themes/abridge/netlify.toml netlify.toml
rsync themes/abridge/package_abridge.js package_abridge.js
rsync themes/abridge/package.json package.json

sed -i 's/^#theme = "abridge"/theme = "abridge"/' config.toml

# Add new content
rsync -r themes/abridge/content .

# Run the project
zola serve --interface 0.0.0.0 --base-url {出口IP|域名}
# zola serve --open

#Web server is available at http://0.0.0.0:1111
  • config.toml 包含所有配置值的基本配置。
  • content/_index.md 需要设置分页。
  • COPY-TO-ROOT-SASS/abridge.scss 重写以自定义 Abridge 变量。
  • netlify.toml 使用 Netlfiy 部署存储库的设置。
  • package_abridge.js 节点脚本到:更新 PWA 中的缓存文件列表、缩小 js、捆绑 js
  • package.json 在 nosearch、elasticlunr、tinysearch、stork 之间切换。

5. 使用 Org Mode 搭建个人站点

Org Mode 是 Emacs 内置的最强力的插件,没有之一。可以用来做 GTD,博客/Wiki工具,写书,写论文等。

缺点:插入图片显示比较困难

官网: https://orgmode.org/

在 Emacs 里通过 Org mode 写博客也有很多方式,如以下两种方式:

  • 通过 Org Mode 自带的 ox-publish 机制导出为静态 HTML 站点
  • 通过 ox-hugo 插件,利用 hugo 的强大功能导出为好看的博客

通过 ox-publish 写博客

我们需要对 ox-publish 做一些基础的配置:

(require 'ox-publish)
(setq org-html-validation-link nil)

(setq org-publish-project-alist
      '(
        ;; notes component
        ("site-orgs"
         :base-directory "~/site/org"
         :base-extension "org"
         :html-link-home "index.html"
         :publishing-directory "~/site-html/"
         :recursive t
         :publishing-function org-html-publish-to-html
         :headline-levels 5
         :auto-preamble t
         :auto-sitemap t
         :sitemap-filename "sitemap.org"
         :sitemap-title "Sitemap"
         )
        ;; static component
        ("site-static"
         :base-directory "~/site/static/"
         :base-extension "css\\|js\\|png\\|jpg\\|gif\\|pdf\\|mp3\\|ogg\\|swf"
         :publishing-directory "~/site-html/static/"
         :recursive t
         :publishing-function org-publish-attachment
         )
        ;; publish component
        ("site" :components ("site-orgs" "site-static"))
        ))

代码很容易理解,一部分处理 org 文件,一部分处理静态文件,发布只需要执行 org-publish ,选择对应的项目即可。

org mode 网站:

6. 使用 MkDocs 搭建个人文档站点

准备

  • Python 已经安装
  • VS code 用户编写文件

6.1. 基础

创建 github 仓库

访问 https://github.com/new 创建仓库并定义名称,这里是 mkdocs-website。勾选添加一个 README 文件,添加 .gitignore 过滤规则选 Python,添加 GPL 许可证。

将仓库克隆到本地

git clone [email protected]:jaspervincent/mkdocs-website.git
cd mkdoc-wesite

创建 Python 虚拟环境

python -m venv venv
source venv/bin/activate  #.\venv\Scripts\activate.bat  windows
pip --version

pip install mkdocs-material

创建 Mkdoc 网站

code . # 用 vscode 打开项目根文件夹

在 vs code 终端菜单中选择新建一个终端,并输入命令

mkdocs new . # 创建站点,同时会生成 2 个新文件

INFO    -  Writing config file: .\mkdocs.yml
INFO    -  Writing initial docs: .\docs\index.md
  • docs/index.md 初始索引文件
  • mkdocs.yml

运行 mkdoc 网站

mkdocs serve

浏览器访问 http://127.0.0.1:8000/ 默认主题

安装 Material 插件

编辑 mkdocs.yaml 文件

site_name: Mkdocs website
theme:
  name: material

保存后自动生效。

添加新特性

编辑 mkdocs.yaml 文件

site_name: Mkdocs website
theme:
  name: material
  features:
    - navigation.tabs
    - navigation.sections
    - toc.integrate
    - navigation.top
    - search.suggest
    - search.highlight
    - content.tabs.link
    - content.code.annotation
    - content.code.copy #代码复制
  language: en
  palette: #调色板
    - scheme: default
      toggle:
        icon: material/toggle-switch-off-outline 
        name: Switch to dark mode
      primary: indigo #teal
      accent: indigo #purple 
    - scheme: slate 
      toggle:
        icon: material/toggle-switch
        name: Switch to light mode    
      primary: indigo #teal
      accent: indigo #lime

添加页面

在 docs 目录下创建新文件, page2.md

# Page 2

## Another heading

Some more example text

添加社交图标

编辑 mkdocs.yaml 文件

extra:
  social: # 社交
    - icon: fontawesome/brands/github-alt
      link: https://github.com/jaspervincent/mkdocs-website
    - icon: fontawesome/brands/twitter
      link: https://twitter.com/TheJamesWillett
    - icon: fontawesome/brands/linkedin
      link: https://www.linkedin.com/in/willettjames/

添加著作版权

编辑 mkdocs.yaml 文件

copyright: |
  &copy; 2024 <a href="https://github.com/jaspervincent"  target="_blank" rel="noopener">Jasper Hsu</a>

配置 markdown 扩展代码高亮

编辑 mkdocs.yaml 文件

markdown_extensions:
  - pymdownx.highlight:
      anchor_linenums: true
  - pymdownx.inlinehilite
  - pymdownx.snippets
  - admonition
  - pymdownx.arithmatex:
      generic: true
  - footnotes
  - pymdownx.details
  - pymdownx.superfences
  - pymdownx.mark
  - attr_list
  - pymdownx.emoji:
      emoji_index: !!python/name:materialx.emoji.twemoji
      emoji_generator: !!python/name:materialx.emoji.to_svg

修改 docs/index.md 文件验证代码高亮

# Mkdocs-website

For full documentation visit [mkdocs.org](https://www.mkdocs.org/)

## Code Annotation Examples

### Codeblocks 代码块

Some `Code` goes here.

### Plain codeblock 普通代码块

```
Some code here
def myfunction()
// some comment
```

#### Code for a specific language 特定语言的代码

Some more code with the `py` at the start:

```py
import tensorflow as tf
def whatever()
```
#### With a title 带标题

```py title="bubble_sort.py"
def bubble_sort(items):
    for i in range(len(items)):
        for j in range(len(items) - 1 - i):
            if items[j] > items[j + 1]:
                items[j], items[j + 1] = items[j + 1], items[j]
```

#### With line numbers 有行号

```py linenums="1"
def bubble_sort(items):
    for i in range(len(items)):
        for j in range(len(items) - 1 - i):
            if items[j] > items[j + 1]:
                items[j], items[j + 1] = items[j + 1], items[j]
```

#### Highlighting lines 突出显示行

```py hl_lines="2 3"
def bubble_sort(items):
    for i in range(len(items)):
        for j in range(len(items) - 1 - i):
            if items[j] > items[j + 1]:
                items[j], items[j + 1] = items[j + 1], items[j]
```

添加图标和 Emojs 表情符号

修改 docs/index.md 文件验证代码高亮

## Icons and Emojs

:smile: 

:fontawesome-regular-face-laugh-wink:

:fontawesome-brands-twitter:{ .twitter }

:octicons-heart-fill-24:{ .heart }

Github Pages 发布

项目根目录创建文件夹 .github/workflows ,创建 ci.yaml 文件

name: ci 
on:
  push:
    branches:
      - master 
      - main
permissions:
  contents: write
jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-python@v4
        with:
          python-version: 3.x
      - uses: actions/cache@v2
        with:
          key: ${{ github.ref }}
          path: .cache
      - run: pip install mkdocs-material
      - run: pip install pillow cairosvg
      - run: mkdocs gh-deploy --force

终端命令输入如下命令,提交

git add .
git commit -m "first commit"
git push origin main

浏览器访问 github 仓库, 点击 Settings –> pages,Branch 选 gh-pages 分支,保存

构建结构后,访问 https://jaspervincent.github.io/mkdocs-website

MkDoc 网站:

7. 使用 Github Issue 作为站点

基本概念

  • issue:每个 issue 即是一篇博文
  • labels:对应博文的 tags
  • milestone:对应博文的 categories

主要场景,如文章的发布、更新、删除都可以完成,操作上十分方便

  • 写一篇文章时,可以利用 GitHub Issues 强大的编辑功能,支持 Markdown,所见即所得
  • 发布文章时,2 步:
    • 1)添加的 label 为 post;带有 post 标签的 issues 才会导出为博客。
    • 2)关闭 issue,开始博文发布流程。
  • 更新文章时,3 步
    • 1)重新打开 issue
    • 2)编辑对应的 issue
    • 3)关闭 issue
  • 删除文章时,3 步
    • 1)重新打开 issue
    • 2)移除标签 post
    • 3)关闭 issue

Issue 网站:

8. CDN加速

8.1. Cloudflare pages

网站托管由github pages 迁移到 https://pages.cloudflare.com

9. 文本

9.1. Markdown

Markdown 是一种轻量级标记语言,可用于向纯文本文档添加格式元素。Markdown 由 John Gruber 于 2004 年创建,现在是世界上最受欢迎的标记语言之一。

参考:

9.2. ReStructuredText

reStructuredText 是扩展名为.rst的纯文本文件,含义为"重新构建的文本"",也被简称为:RST或reST;是Python编程语言的Docutils项目的一部分,Python Doc-SIG (Documentation Special Interest Group)。该项目类似于Java的JavaDoc或Perl的POD项目。 Docutils 能够从Python程序中提取注释和信息,格式化成程序文档。

.rst 文件是轻量级标记语言的一种,被设计为容易阅读和编写的纯文本,并且可以借助Docutils这样的程序进行文档处理,也可以转换为HTML或PDF等多种格式,或由Sphinx-Doc这样的程序转换为LaTex、man等更多格式。

RST 和 MD 之间的选择取决于您项目的特定需求和个人喜好。如果您需要更复杂的格式和文档结构,RST 可能是更好的选择。但是,如果您更喜欢更简单的语法以及与各种工具和平台的更大兼容性,那么 MD 可能是您的不二之选。

实例:

参考: