About the blog

This blog is based on vuepress1.x. Write down some technical knowledge. Here’s how to build a tech blog from scratch with Vuepress.

Vuperss profile

Vuepress is a generator for static websites in the Vue ecosystem. It has good support for technical types of blogs, few configurations, quick to use, and a pleasing UI style. This blog site is built using vuepress1.x. In addition to this blog, the following sites are also used by Vuepress

  • vuepress
  • vue

start

  • By default, you have the Node environment on your computer
  • Node.js is later than 8.6
  • It’s best if you’ve read the official documentation

This tutorial will create two projects on Github, one for blogging and one for presenting blogs. In fact, you can also synthesize a project, depending on personal preference.

Install vuepress

Vuepress1. X is used in this blog, so you need to install it like this:

    yarn global add vuepress@next // OR npm install -g vuepress@next

Copy the code

If you want to use Vuepress0.x, follow the following installation

    yarn global add vuepress // OR npm install -g vuepress
Copy the code

There is little difference between the two versions of the blog for beginners, this blog recommends using vuepress1.x.

Building a Blog project

It is divided into four parts

  • Build an initial project and use VuePress to blog
  • Configure the navigation and sidebar
  • Build and publish
  • Automated deployment

To begin, I’ll show you the directory structure of my blog:

Part ONE: Building the project

Create a write-blog folder and initialize the project in Part 1


mkdir writ-blog
cdWrit-blog NPM init -y mkdir docs // This folder is where all blogs are placedcdDocs touch readme. md // Create the reademe file, the home pageCopy the code

The initialized directory structure is as follows:

.├ ─ docs ├─ download.txtCopy the code

Note that the docs folder is where all your blogs are located, and the readme. md file at the root of the docs folder will become the home page of your blog site after being compiled by Vuepress!!

In the readme. md file in the docs directory, write the following:

---
home: true
heroImage: /logo.png
actionText: introduce -
actionLink: /blog/
features:
- title: The framework
  details: Study and practice of Flutter, Vue, React, Abgular, Flutter.
- title: Work notes
  details: A good memory is not as good as bad writing. Record some problems and solutions encountered in ordinary work.
- title: Front-end visualization
  details: Front-end visualization knowledge, including WebGL, Canvas, GLSL, etc.
- title: The back-end
  details: How can the front-end not know something about the back-end? Some personal learning and practice with the back end.
- title: Development Environment Configuration
  details: Sometimes the configuration of the development environment is also a headache, Windows and MAC are different below, tool proficiency directly determines the speed of development, so leave a message to check.
footer: MIT Licensed | Copyright © 2019 - present chenfeng...Copy the code

Note: this file is the home page of your blog (index.html). ‘ ‘home: true’ ‘is required

After initialization, add two commands to script in package.json:


"dev": "vuepress dev docs"."build": "vuepress build docs".Copy the code

Then run NPM run dev, open the service in a browser, and a page will appear that looks something like this

Part two: Configuring the navigation and sidebar

The directory structure for Part 2 is as follows:

.├ ─ ├─ customs.txt ├─ customs.txt ├─ customs.txtCopy the code

You will notice that there is a. Vuepres folder in this step, and the configuration for vuepress is in this folder. Here is the configuration for the navigation bar and the sidebar. The basic configuration in vuepress/config is as follows:


module.exports = {
    title: 'chenfeng\'s blog'.description: 'Chenfeng's Personal blog',}Copy the code

When you have completed the above steps, the web page rendered in your local dev environment should contain a header and a description.

The following configuration content is the configuration of my website:


module.exports = {
    title: 'chenfeng\'s blog'.description: 'Chenfeng's Personal blog'.head: [ // The tag injected into the HTML  of the current page
        ['link', { rel: 'icon'.href: '/logo.png'}].// Add a custom favicon
        ['link', { rel: 'manifest'.href: '/logo.png' }],
        ['link', { rel: 'apple-touch-icon'.href: '/logo.png' }],
        ['link', { rel: 'mask-icon'.href: '/logo.png'.color: '#3eaf7c' }],
        ['meta', { 'http-quiv': 'pragma'.cotent: 'no-cache' }],
        ['meta', { 'http-quiv': 'expires'.cotent: '0' }],
        ['meta', { 'http-quiv': 'pragma'.cotent: 'no-cache, must-revalidate'}]],serviceWorker: true.// Whether to enable PWA
    base: '/'.// This is the configuration associated with deploying to Github
    markdown: {
        lineNumbers: true // The code block displays the line number
    },
    themeConfig: {
        nav: [{text: 'home'.link: '/' },
            {
                text: 'base'.items: [{text: 'JavaScript'.link: '/basis/JavaScript/' },
                    { text: 'HTML'.link: '/basis/HTML/' },
                    { text: 'CSS'.link: '/basis/CSS/' },
                    { text: 'TypeScript'.link: '/basis/CSS/']}, {},text: 'frame'.items: [{text: 'Vue'.link: '/frame/Vue/' },
                    { text: 'React'.link: '/frame/React/' },
                    { text: 'Angular'.link: '/frame/Angular/' },
                    { text: 'Flutter'.link: '/frame/Flutter/'}]}, {text: 'Working notes'.link: '/work/' },
            { text: 'Front-end Visualization'.link: '/visualization/' },
            { text: 'Environment Configuration'.link: '/devconfig/' },
            { text: 'Github'.link: 'https://github.com/soyomo'}].sidebar: {
            '/blog/': getSidebar('blog'),
            '/frame/': getSidebar('frame'),
            '/basis/': getSidebar('basis')},sidebarDepth: 2.// The sidebar shows 2 levels}};function getSidebar(barName) {
    const sidebar = {
        frame: [
            '/frame/'.'/frame/Vue/'.'/frame/React/'.'/frame/Angular/'].blog: [
            '/blog/'].basis: []}return sidebar[barName]
}
Copy the code

If you feel that the file is too long, you can put nav and sidebar in a separate file. My.vuepress file directory structure looks like this:

The nav.js content is as follows:

module.exports = [
    { text: 'home'.link: '/' },
    {
        text: 'base'.items: [{text: 'JavaScript'.link: '/basis/JavaScript/' },
            { text: 'HTML'.link: '/basis/HTML/' },
            { text: 'CSS'.link: '/basis/CSS/' },
            { text: 'TypeScript'.link: '/basis/CSS/']}, {},text: 'frame'.items: [{text: 'Vue'.link: '/frame/Vue/' },
            { text: 'React'.link: '/frame/React/' },
            { text: 'Angular'.link: '/frame/Angular/' },
            { text: 'Flutter'.link: '/frame/Flutter/'}]}, {text: 'Working notes'.link: '/work/' },
    { text: 'Front-end Visualization'.link: '/visualization/' },
    { text: 'Environment Configuration'.link: '/devconfig/' },
    { text: 'Github'.link: 'https://github.com/soyomo'}]Copy the code

Then import this file into config.js. Navigation still won’t work at this point because you won’t be able to find the path. Therefore, it is necessary to set up the folders corresponding to the navigation, these folders are set up in the docs directory, the corresponding files of each page of the blog are in the docs directory!! Once these folders are set up, create a readme. md file, because this file matches the default path in Vuepress when you write only folders. My docs file directory is as follows:

Run the project at this time, and the corresponding page for each navigation bar should be blank.

For docs/.vuepress/public:

It is for storing public resources. I put the logo of my blog in this folder. It is suggested that the static resources of each blog should be placed in the directory of that blog instead of all in public. For example, I have put all the pictures in this tutorial under the corresponding table of contents of this article:

The path to the blog folder: write-blog/docs/blog;

The MANIFEST configuration for the PWA also needs to be placed in this folder. Manifest.json contents:

{
    "name": "chenfeng"."short_name": "feng"."start_url": "index.html"."display": "standalone"."background_color": "#2196f3"."description": "Personal Website"."theme_color": "blue"."icons": [{"src": "./logo.jpg"."sizes": "144x144"."type": "image/png"}]."related_applications": [{"platform": "web"
      },
      {
        "platform": "play"."url": "https://play.google.com/store/apps/details?id=cheeaun.hackerweb"}}]Copy the code

That’s it for part two.

Part three: Build and publish

In this part, you need to create a new project on Github. My project is a project, which is actually called Github Pages.

{your username}.github. IO
https://{username}.github.io/

 "scripts": {
    "dev": "vuepress dev docs"."build": "vuepress build docs"."deploy": "bash deploy.sh",},Copy the code

Create a deploy.sh file in the same directory as the write-blog file and the contents are as follows:

#! /usr/bin/env sh
Make sure the script throws any errors it encounters
set -e
npm install -g vuepress@next
Generate static files
npm run build

Go to the generated folder
cd docs/.vuepress/dist

# if publish to custom domain name
# echo 'www.example.com' > CNAME

git init
git add -A
git commit -m 'deploy'

# if posted to https://
      
       .github
      
# git push -f https://${token}@${address} master:master
git push -f[email protected]:{your username}/{your username}.github.io. Git masterGithub. IO /
      
# git push -f [email protected]:<USERNAME>/<REPO>.git master:gh-pages

cd -
Copy the code

Github. IO will be published to {username}.github. IO and will be accessible via a connection. This is basically enough to write a blog, but having to go to NPM run every time you write is not very friendly, so automated deployment will help.

Part four: Travis Automated Deployment

For Travis, if you haven’t heard of it yet, here’s a tutorial to get you started. In this link, it is divided into three parts:

  • Log in to Travis using your Github account
  • Apply for Personal Access Tokens on Github
  • Set environment variables in Travis

Personal Access Tokens

Go to Github setting to apply for Personal Access Tokens

Set Environment Variables :100:

Go to More OPtions in your project on Travis (upper right corner of image below):

Soyomo.github. IO is only an empty shell, only useful in two places. The first is created according to the specifications of GitPage. The second is to use the project’s Github address when setting the environment variable address in Travis during deployment. Other times it doesn’t.

github.com/soyomo/soyomo.github.io.git

! /usr/bin/env shMake sure the script throws any errors it encounters
set -e
npm install -g vuepress@next
Generate static files
npm run build

Go to the generated folder
cd docs/.vuepress/dist

# if publish to custom domain name
# echo 'www.example.com' > CNAME

git init
git add -A
git commit -m 'deploy'

# if posted to https://
      
       .github
      
git push -f https://${token}@${address} master:master

Github. IO /
      
# git push -f [email protected]:<USERNAME>/<REPO>.git master:gh-pages

cd -
Copy the code

Then, create a.travis. Yml file under the project directory with the following contents:

sudo: required
language: node_js
node_js: stable
script: bash ./deploy.sh
branches:
  only:
  - master
notifications:
  email: false
Copy the code

This way, Travis will automatically build your {username}.github. IO project for you every time you submit a change to your write-blog project.

An error

The following error occurs on Travis when github does not apply for a token:

subsequent

After all the above steps are done, you have a simple blog site in your hands. This is the time to treat yourself to a cup of coffee or a nice meal.

Adding a comment system

Before adding comments you need to prepare clientID and clientSecret, which are generated by registering a new OAuth Application here.

soyomo.github.io

My blog is currently using: Vssue.Vssue is a VUE-driven issue-based plug-in that is very convenient to use in VuePress. Here is the official documentation for using Vssue in VuePress, if you don’t want to read it, there are only two steps.

Step 1 Install the plug-in

npm install @vssue/vuepress-plugin-vssue
npm install @vssue/api-github-v3
Copy the code

The second step is to use the plug-in

Add plugins to.vuepress/config.js:

plugins: {
    '@vssue/vuepress-plugin-vssue': {
      // Set 'platform' instead of 'API'
      platform: 'github'.locale: 'zh'.// Language Settings

      Other Vssue configurations
      owner: 'OWNER_OF_REPO'.// Your Github account name
      repo: 'NAME_OF_REPO'.// Your Github blog repository I entered soyomo
      clientId: 'YOUR_CLIENT_ID'.// You applied for clientId on Github
      clientSecret: 'YOUR_CLIENT_SECRET'.// clientSecret requested on Github}},Copy the code

Then use it as a component in the MD document by adding the following sentence to the bottom of the MD document:

<Vssue title="Vssue Demo" />
Copy the code

An alternative to the comment system

In the first version of my blog, I used GitTalk to make comments. The principle of GitTalk is to make use of github issue to make comments on blogs. The specific implementation is in the.vuepress/ enhanceapp.js file. For enhanceapp.js, please refer to the official vuepress documentation. For this blog project, just type the following code in this file:


function integrateGitalk(router) {
    const linkGitalk = document.createElement('link');
    linkGitalk.href = 'https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css';
    linkGitalk.rel = 'stylesheet';
    document.body.appendChild(linkGitalk);
    const scriptGitalk = document.createElement('script');
    scriptGitalk.src = 'https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js';
    document.body.appendChild(scriptGitalk);
  
    router.afterEach((to) = > {
      if (scriptGitalk.onload) {
        loadGitalk(to);
      } else {
        scriptGitalk.onload = (a)= >{ loadGitalk(to); }}});function loadGitalk(to) {
      let commentsContainer = document.getElementById('gitalk-container');
      if(! commentsContainer) { commentsContainer =document.createElement('div');
        commentsContainer.id = 'gitalk-container';
        commentsContainer.classList.add('content');
      }
      const $page = document.querySelector('.page');
      if ($page) {
        $page.appendChild(commentsContainer);
        if (typeofGitalk ! = ='undefined' && Gitalk instanceof Function) { renderGitalk(to.fullPath); }}}function renderGitalk(fullPath) {
      const gitalk = new Gitalk({
        clientID: '* * * *'.// Generated on Github
        clientSecret: '* * * *'.// Come from Github development generated on Github
        repo: '* * * *'.// The name of your blog's repository
        owner: '* * * *'.// Your user name on githug
        admin: ['* * * *'].// Manage members
        id: 'comment'.distractionFreeMode: false.language: 'zh-CN'}); gitalk.render('gitalk-container'); }}export default ({Vue, options, router}) => {
    try {
      document && integrateGitalk(router)
    } catch (e) {
      console.error(e.message)
    }
  }

Copy the code

Note that because in the development environment our project is using ‘write-blog’ and the repO in the configuration is the project name of the blog, the login in the development environment will not be successful, but if the development environment already has a comment section, the configuration will be successful