最快用vuepress+github搭建一个博客

1,620 阅读2分钟

vuepress是vue提供的一个文档页生成工具,虽然官方还没有实现博客适配,但是现在可以通过一些小配置文件的修改,作为一个自己的博客生成工具

博客预览

事前准备

为了建立博客,我们需要一个存放博客页的地方,最理想的还是github啦

建立仓库

虽然现在github为每个仓库都提供了github pages服务,不过我们还是需要github提供的耳机线域名,所以

  1. 创建一个repository 这个repository的名字还有要求必须是<你的用户名>.github.io,像我就是mizuka-wu.github.io
  2. 申请域名和绑定ssl 在仓库的settings中Custom domain中可以填写自己的域名,当然直接在项目目录下建立CNAME文件填写自己的域名也可以,ssl可以使用certbot自主申请三个月的(三个月续期就可以无限使用了)
  3. 下载git,将这个git项目下载到本地吧

建立vuepress工作流

为什么使用?主要我觉得。。默认主题比较好看吧

基本环境搭建(npm)

  1. npm init(建立个package.json)
  2. www.gitignore.io/下载gitignore文件 推荐wget https://www.gitignore.io/api/node,webstorm+all,visualstudiocode -o .gitignore
  3. 建立blog文件夹(不用vuepress使用的doc因为我们不是建立文档

vuepress配置

vuepress生成依赖于.vuepress 当然使用默认配置也可以

我们最终是用vuepress构建我们写好的md文件,由于github.io相当于一个静态资源服务器,所以路径就变得很重要了, 所以配置上我们基本就是将本身的build路径改为根目录下的/post/ 然后将index.html这一类的资源构建完成后放入到根目录下

  • 增加vuepress npm i vuepress -D
  • 在blog文件夹下建立.vuepress文件夹 cd blog && mkdir .vuepress
  • .vuepress文件夹下建立config.js basePath保证输出位置和生成文件引用资源位置正确
const basePath = 'post'

module.exports = {
    // meta
    title: '我的博客', 
    description: '万事皆虚,万事皆允',
    // vuepress config
    dest: basePath,
    base: `/${basePath}/`,
    serviceWorker: true,
    evergreen: true,
    ga: 'UA-112738831-1'
}
  • package.json下增加script
  "scripts": {
    "dev": "vuepress dev blog",
    "build": "vuepress build blog",
  },
  • 构建结束后自动移动文件-我的方案是通过spwan写脚本,方便日后增加文件,如果嫌麻烦 直接build命令下增加&& cp post/index.html ./

推荐一个node可以使用es module的方案esm

/**
 * Build blog
 * @author Mizuka <mizuka.wu@outlook.com>
 */
import spawn from 'cross-spawn'
import { copyFile, writeFileSync } from 'fs'
import config from './blog/.vuepress/config'

const builder = spawn('vuepress', ['build', 'blog'])
builder.stdout.on('data', function (s) {
  console.log(s.toString())
})

builder.stdout.on('end', function () {
  if (config.postsAsRoot) {
    copyFile('post/index.html', 'index.html', (err) => {
      if (err) {
        console.error(err)
        throw err
      }
      console.log('copy /post/index.html to /')
    })
  }
})

开始编写吧!

剩下的只是在blog下按照自己的喜好编写markdown文件就好啦,构建完毕发布到github上看看呗

tip 一个主页以及显示所有文章

vuepress官方提供了一个主页生成的语法 这里说一下怎么显示所有的文档

vuepress支持在markdown中写vue!

vuepress提供了很多信息,比如$site.pages

在blog/README.md下增加一段vue代码

# 所有文章
<div style="display: flex; flex-direction: column">
    <div v-for="page of $site.pages.filter(item => item.path !== '/')" :key="page.key" style="padding: 20px 0; max-width: 33%;">
        <router-link :to="page.path">
            {{page.title}}
            <div style="color: #c2c5cd; font-size: .5rem;">{{(page.frontmatter.tags || ['无标签']).join(',  ')}}</div>
        </router-link>
    </div>
</div>

默认的工程文件可以来我的github博客直接下载呀~