超详细Hexo+Github博客搭建教程

2,223 阅读6分钟

利用 Hexo + GitHub Page 搭建技术 blog ,实现了属于自己独有的博客,自己定义了一个域名:gain-wyj.cn/。里面包含了众多的干货,欢迎大家前来观看。

我的博客源代码地址

大家可以直接素质二连,star&fork我的博客源代码:github.com/gain-wyj/wy…,然后改改配置就可以写文章啦。具体使用说明可在另一个分支main里头的README.md查看。

首先运行git@github.com:gain-wyj/wyj-matery-modified.git将所有文件下载到本地。

还缺一个字体(为图片添加水印需要用到),去C:\Windows\Fonts下找到STSong Regular,复制到wyj-matery-modified文件夹下。

快速搭建

如果你不想自己从头开始慢慢自定义主题的话,可以直接下载我的修改好的主题,然后稍微修改几个地方就好了:

  • 根目录配置文件_config.yml和主题目录配置文件_config.yml中修改个人信息。
  • 根目录配置文件中修改deploy一栏的repository
  • 根目录配置文件中修改baidu_url_submit一栏的token
  • 主题配置文件中修改gitalk一栏,修改方法见正文。
  • 当然前提是个性化设置章节之前的环境还是需要配置好!

平时常用命令

hexo g  # 生成博客网页文件
hexo s  # 本地预览博客
hexo d  # 上传网页文件到github

博客源代码下载

如果大家不想这么麻烦的装一堆东西,然后还要自己修改bug,那么只需要做好上面的准备工作,然后下载我的源代码,改改个人配置就行了。

源码地址:github.com/gain-wyj/wy…。大家可以直接下载下来使用,修改个人配置信息即可,当然环境要先搭好。

如果大家下载好了源代码,就可以直接使用了,基本可以跳过文章后面的部分了!喜欢的记得star并fork哦!

安装Node.js

首先下载稳定版Node.js,我这里给的是64位的。

安装选项全部默认,一路点击Next

最后安装好之后,按Win+R打开命令提示符,输入node -vnpm -v,如果出现版本号,那么就安装成功了。

添加国内镜像源

如果没有梯子的话,可以使用阿里的国内镜像进行加速。

npm config set registry https://registry.npm.taobao.org

安装Git

为了把本地的网页文件上传到github上面去,我们需要用到分布式版本控制工具————Git[下载地址]

安装选项还是全部默认,只不过最后一步添加路径时选择Use Git from the Windows Command Prompt,这样我们就可以直接在命令提示符里打开git了。

安装完成后在命令提示符中输入git --version验证是否安装成功。

安装Hexo

在合适的地方新建一个文件夹,用来存放自己的博客文件,比如我的博客文件都存放在D:\study\program\blog目录下。

在该目录下右键点击Git Bash Here,打开git的控制台窗口,以后我们所有的操作都在git控制台进行,就不要用Windows自带的控制台了。

定位到该目录下,输入npm i hexo-cli -g安装Hexo。会有几个报错,无视它就行。

安装完后输入hexo -v验证是否安装成功。

然后就要初始化我们的网站,输入hexo init初始化文件夹,接着输入npm install安装必备的组件。

这样本地的网站配置也弄好啦,输入hexo g生成静态网页,然后输入hexo s打开本地服务器,然后浏览器打开http://localhost:4000/,就可以看到我们的博客啦。

ctrl+c关闭本地服务器。

连接Github与本地

首先右键打开git bash,然后输入下面命令:

git config --global user.name "xxxxx"
git config --global user.email "xxxxx@qq.com"

用户名和邮箱根据你注册github的信息自行修改。

然后生成密钥SSH key:

ssh-keygen -t rsa -C "xxxxx@qq.com"

打开github,在头像下面点击settings,再点击SSH and GPG keys,新建一个SSH,名字随便。

git bash中输入

cat ~/.ssh/id_rsa.pub

将输出的内容复制到框中,点击确定保存。

输入ssh -T git@github.com,出现你的用户名,那就成功了。 在这里插入图片描述 打开博客根目录下的_config.yml文件,这是博客的配置文件,在这里你可以修改与博客相关的各种信息。

修改最后一行的配置:

deploy:
  type: git
  repository: https://github.com/gain-wyj/gain-wyj.github.io
  branch: master

repository修改为你自己的github项目地址。

写文章、发布文章

首先在博客根目录下右键打开git bash,安装一个扩展npm i hexo-deployer-git

然后输入hexo new post "article title",新建一篇文章。

然后打开D:\study\program\blog\source\_posts的目录,可以发现下面多了一个文件夹和一个.md文件,一个用来存放你的图片等数据,另一个就是你的文章文件啦。

编写完markdown文件后,根目录下输入hexo g生成静态网页,然后输入hexo s可以本地预览效果,最后输入hexo d上传到github上。这时打开你的github.io主页就能看到发布的文章啦。

gain-wyj.cn/

首页/

推荐文章/

博客列表/

标签/

在这里插入图片描述

分类/

归档/

关于/

友情链接/

留言板/

增加建站时间

修改/themes/matery/layout/_partial/footer.ejs文件,在最后加上

<script language=javascript>
    function siteTime() {
        window.setTimeout("siteTime()", 1000);
        var seconds = 1000;
        var minutes = seconds * 60;
        var hours = minutes * 60;
        var days = hours * 24;
        var years = days * 365;
        var today = new Date();
        var todayYear = today.getFullYear();
        var todayMonth = today.getMonth() + 1;
        var todayDate = today.getDate();
        var todayHour = today.getHours();
        var todayMinute = today.getMinutes();
        var todaySecond = today.getSeconds();
        /* Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
        year - 作为date对象的年份,为4位年份值
        month - 0-11之间的整数,做为date对象的月份
        day - 1-31之间的整数,做为date对象的天数
        hours - 0(午夜24点)-23之间的整数,做为date对象的小时数
        minutes - 0-59之间的整数,做为date对象的分钟数
        seconds - 0-59之间的整数,做为date对象的秒数
        microseconds - 0-999之间的整数,做为date对象的毫秒数 */
        var t1 = Date.UTC(2017, 09, 11, 00, 00, 00); //北京时间2018-2-13 00:00:00
        var t2 = Date.UTC(todayYear, todayMonth, todayDate, todayHour, todayMinute, todaySecond);
        var diff = t2 - t1;
        var diffYears = Math.floor(diff / years);
        var diffDays = Math.floor((diff / days) - diffYears * 365);
        var diffHours = Math.floor((diff - (diffYears * 365 + diffDays) * days) / hours);
        var diffMinutes = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours) / minutes);
        var diffSeconds = Math.floor((diff - (diffYears * 365 + diffDays) * days - diffHours * hours - diffMinutes * minutes) / seconds);
        document.getElementById("sitetime").innerHTML = "本站已运行 " +diffYears+" 年 "+diffDays + " 天 " + diffHours + " 小时 " + diffMinutes + " 分钟 " + diffSeconds + " 秒";
    }/*因为建站时间还没有一年,就将之注释掉了。需要的可以取消*/
    siteTime();
</script>

修复代码块行号不显示bug

修改themes/matery/source/css/matery.css第95行左右的precode两段改为如下代码:

pre {
    /* padding: 1.5rem !important; */
    padding: 1.5rem 1.5rem 1.5rem 3.3rem !important;
    margin: 1rem 0 !important;
    background: #272822;
    overflow: auto;
    border-radius: 0.35rem;
    tab-size: 4;
}

code {
    padding: 1px 5px;
    font-family: Inconsolata, Monaco, Consolas, 'Courier New', Courier, monospace;
    /* font-size: 0.91rem; */
    color: #e96900;
    background-color: #f8f8f8;
    border-radius: 2px;
}

添加雪花特效

首先在themes/matery/source/libs/others下新建文件snow.js,并插入如下代码:

/*样式一*/
(function($){
    $.fn.snow = function(options){
    var $flake = $('<div id="snowbox" />').css({'position': 'absolute','z-index':'9999', 'top': '-50px'}).html('&#10052;'),
    documentHeight  = $(document).height(),
    documentWidth   = $(document).width(),
    defaults = {
        minSize     : 10,
        maxSize     : 20,
        newOn       : 1000,
        flakeColor  : "#AFDAEF" /* 此处可以定义雪花颜色,若要白色可以改为#FFFFFF */
    },
    options = $.extend({}, defaults, options);
    var interval= setInterval( function(){
    var startPositionLeft = Math.random() * documentWidth - 100,
    startOpacity = 0.5 + Math.random(),
    sizeFlake = options.minSize + Math.random() * options.maxSize,
    endPositionTop = documentHeight - 200,
    endPositionLeft = startPositionLeft - 500 + Math.random() * 500,
    durationFall = documentHeight * 10 + Math.random() * 5000;
    $flake.clone().appendTo('body').css({
        left: startPositionLeft,
        opacity: startOpacity,
        'font-size': sizeFlake,
        color: options.flakeColor
    }).animate({
        top: endPositionTop,
        left: endPositionLeft,
        opacity: 0.2
    },durationFall,'linear',function(){
        $(this).remove()
    });
    }, options.newOn);
    };
})(jQuery);
$(function(){
    $.fn.snow({ 
        minSize: 5, /* 定义雪花最小尺寸 */
        maxSize: 50,/* 定义雪花最大尺寸 */
        newOn: 300  /* 定义密集程度,数字越小越密集 */
    });
});
/*样式二*/
/* 控制下雪 */
function snowFall(snow) {
    /* 可配置属性 */
    snow = snow || {};
    this.maxFlake = snow.maxFlake || 200;   /* 最多片数 */
    this.flakeSize = snow.flakeSize || 10;  /* 雪花形状 */
    this.fallSpeed = snow.fallSpeed || 1;   /* 坠落速度 */
}
/* 兼容写法 */
requestAnimationFrame = window.requestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.webkitRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    window.oRequestAnimationFrame ||
    function(callback) { setTimeout(callback, 1000 / 60); };

cancelAnimationFrame = window.cancelAnimationFrame ||
    window.mozCancelAnimationFrame ||
    window.webkitCancelAnimationFrame ||
    window.msCancelAnimationFrame ||
    window.oCancelAnimationFrame;
/* 开始下雪 */
snowFall.prototype.start = function(){
    /* 创建画布 */
    snowCanvas.apply(this);
    /* 创建雪花形状 */
    createFlakes.apply(this);
    /* 画雪 */
    drawSnow.apply(this)
}
/* 创建画布 */
function snowCanvas() {
    /* 添加Dom结点 */
    var snowcanvas = document.createElement("canvas");
    snowcanvas.id = "snowfall";
    snowcanvas.width = window.innerWidth;
    snowcanvas.height = document.body.clientHeight;
    snowcanvas.setAttribute("style", "position:absolute; top: 0; left: 0; z-index: 1; pointer-events: none;");
    document.getElementsByTagName("body")[0].appendChild(snowcanvas);
    this.canvas = snowcanvas;
    this.ctx = snowcanvas.getContext("2d");
    /* 窗口大小改变的处理 */
    window.onresize = function() {
        snowcanvas.width = window.innerWidth;
        /* snowcanvas.height = window.innerHeight */
    }
}
/* 雪运动对象 */
function flakeMove(canvasWidth, canvasHeight, flakeSize, fallSpeed) {
    this.x = Math.floor(Math.random() * canvasWidth);   /* x坐标 */
    this.y = Math.floor(Math.random() * canvasHeight);  /* y坐标 */
    this.size = Math.random() * flakeSize + 2;          /* 形状 */
    this.maxSize = flakeSize;                           /* 最大形状 */
    this.speed = Math.random() * 1 + fallSpeed;         /* 坠落速度 */
    this.fallSpeed = fallSpeed;                         /* 坠落速度 */
    this.velY = this.speed;                             /* Y方向速度 */
    this.velX = 0;                                      /* X方向速度 */
    this.stepSize = Math.random() / 30;                 /* 步长 */
    this.step = 0                                       /* 步数 */
}
flakeMove.prototype.update = function() {
    var x = this.x,
        y = this.y;
    /* 左右摆动(余弦) */
    this.velX *= 0.98;
    if (this.velY <= this.speed) {
        this.velY = this.speed
    }
    this.velX += Math.cos(this.step += .05) * this.stepSize;

    this.y += this.velY;
    this.x += this.velX;
    /* 飞出边界的处理 */
    if (this.x >= canvas.width || this.x <= 0 || this.y >= canvas.height || this.y <= 0) {
        this.reset(canvas.width, canvas.height)
    }
};
/* 飞出边界-放置最顶端继续坠落 */
flakeMove.prototype.reset = function(width, height) {
    this.x = Math.floor(Math.random() * width);
    this.y = 0;
    this.size = Math.random() * this.maxSize + 2;
    this.speed = Math.random() * 1 + this.fallSpeed;
    this.velY = this.speed;
    this.velX = 0;
};
// 渲染雪花-随机形状(此处可修改雪花颜色!!!)
flakeMove.prototype.render = function(ctx) {
    var snowFlake = ctx.createRadialGradient(this.x, this.y, 0, this.x, this.y, this.size);
    snowFlake.addColorStop(0, "rgba(255, 255, 255, 0.9)");  /* 此处是雪花颜色,默认是白色 */
    snowFlake.addColorStop(.5, "rgba(255, 255, 255, 0.5)"); /* 若要改为其他颜色,请自行查 */
    snowFlake.addColorStop(1, "rgba(255, 255, 255, 0)");    /* 找16进制的RGB 颜色代码。 */
    ctx.save();
    ctx.fillStyle = snowFlake;
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
    ctx.fill();
    ctx.restore();
};
/* 创建雪花-定义形状 */
function createFlakes() {
    var maxFlake = this.maxFlake,
        flakes = this.flakes = [],
        canvas = this.canvas;
    for (var i = 0; i < maxFlake; i++) {
        flakes.push(new flakeMove(canvas.width, canvas.height, this.flakeSize, this.fallSpeed))
    }
}
/* 画雪 */
function drawSnow() {
    var maxFlake = this.maxFlake,
        flakes = this.flakes;
    ctx = this.ctx, canvas = this.canvas, that = this;
    /* 清空雪花 */
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for (var e = 0; e < maxFlake; e++) {
        flakes[e].update();
        flakes[e].render(ctx);
    }
    /*  一帧一帧的画 */
    this.loop = requestAnimationFrame(function() {
        drawSnow.apply(that);
    });
}
/* 调用及控制方法 */
var snow = new snowFall({maxFlake:60});
snow.start();

然后在主题配置文件里libs.js里添加一行snow: /libs/others/snow.js

themes/matery/layout/layout.ejs里添加如下代码:

<!-- 雪花特效 -->
<% if (theme.snow.enable) { %>
<script type="text/javascript" src="<%- theme.libs.js.snow %>"></script>
<% } %>

最后在主题配置文件最后添加:

# 雪花特效
snow:
  enable: true

添加404页面

原来的主题没有404页面,加一个也不是什么难事。首先在/source/目录下新建一个404.md,内容如下:

---
title: 404
date: 2019-07-19 16:41:10
type: "404"
layout: "404"
description: "你来到了没有知识的荒原 :("
---

然后在/themes/matery/layout/目录下新建一个404.ejs文件,内容如下:

<style type="text/css">
    /* don't remove. */
    .about-cover {
        height: 75vh;
    }
</style>

<div class="bg-cover pd-header about-cover">
    <div class="container">
        <div class="row">
            <div class="col s10 offset-s1 m8 offset-m2 l8 offset-l2">
                <div class="brand">
                    <div class="title center-align">
                        404
                    </div>
                    <div class="description center-align">
                        <%= page.description %>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    // 每天切换 banner 图.  Switch banner image every day.
    $('.bg-cover').css('background-image', 'url(/medias/banner/' + new Date().getDay() + '.jpg)');
</script>

“关于”页面增加简历(可选)

修改/themes/matery/layout/about.ejs,找到<div class="card">标签,然后找到它对应的</div>标签,接在后面新增一个card,语句如下:

<div class="card">
    <div class="card-content">
        <div class="card-content article-card-content">
                <div class="title center-align" data-aos="zoom-in-up">
                    <i class="fa fa-address-book"></i>&nbsp;&nbsp;<%- __('myCV') %>
                </div>
                <div id="articleContent" data-aos="fade-up">
                    <%- page.content %>
                </div>
        </div>
    </div>
</div>

这样就会多出一张card,然后可以在/source/about/index.md下面写上你的简历了,当然这里的位置随你自己设置,你也可以把简历作为第一个card。

资源传送门

  • 关注【做一个柔情的程序猿】公众号
  • 在【做一个柔情的程序猿】公众号后台回复 【python资料】【2020秋招】 即可获取相应的惊喜哦!

「❤️ 感谢大家」

  • 点赞支持下吧,让更多的人也能看到这篇内容(收藏不点赞,都是耍流氓 -_-)
  • 欢迎在留言区与我分享你的想法,也欢迎你在留言区记录你的思考过程