From build to deploy, build a private blog quickly

Posted by shab620 on Tue, 20 Aug 2019 07:06:24 +0200

Sometimes we want a controlled blog to record or share something. The subject matter of this blog is decided by you. It can be technology sharing (programming, Sinicized sharing, etc.) or life feeling.

This article will introduce a controlled blog that can be quickly built and deployed. Before reading this article, I hope you have some knowledge of the following points:

  • Basic use of GIT (version control)
  • The Use of markdown

Why build a blog

Online blogs have many choices. Why do we need to build new blogs from scratch? What are the benefits of building your own blog?

First of all, the "blog controlled" mentioned above refers to the style and content of the blog that can be controlled by oneself and can be changed as one wishes.

Content-controlled means that we know that online blogs are platform-constrained, which means that the content you publish needs to be audited before it can be sent. Some sensitive technical vocabulary may be harmony or deletion of the article. But there is no such problem when you build your own blog. At least you can keep the source files.

Secondly, the style of blog is controlled. Some bloggers'articles on CSDN, a well-known online blog, are indeed valuable for learning, but the problem is that there are too many advertisements on the site, and the reading experience of fonts and typesetting is not very good. But if you build your own blog, you can start optimizing these issues yourself.

But the construction of the blog also needs us to consider the pros and cons from all aspects. Platform blogs will have the corresponding recommendation system, will drain the same type of articles, will do better in SEO than we do.

Personally built blogs, the initial browsing volume is not high, but you can gradually increase the weight of your website through SEO and other ways. Or improve the quality of blogs and dry goods, readers think that articles are valuable, naturally will be collected to form acquaintances.

So what can a blog write about? In daily life, there are many knowledge points are fragmentary. The essence of blogging is to sort out one's own knowledge, and then share these knowledge. There may be doubts about this knowledge, or want to find a solution. What you share can give readers some reference. At the same time, it will also be a virtuous circle, because sharing at the same time, you may also need to query some information, but also to find solutions that others have encountered and shared, is a process of mutual benefit.

Our basic requirement is to sort out and share, so we should pay more attention to the content itself, the layout of the website and so on is to increase the reader's reading experience. So we can use existing blog frameworks to do these things quickly.

Blog framework has many choices, the author chose is Hexo Because it's easy and elegant enough.

start

Hexo dependence Node.js With NPM package management, Node.js usually comes with NPM after installation.

We open the terminal (terminal in Windows PowerShell/cmd.exe, bash, macOS) and enter the following commands:

# Check whether npm is installed successfully
npm -v

# Install hexo cli,
# If the installation speed is too slow, you can install the domestic Taobao image.
# Enter `npm install -g cnpm --registry=https://registry.npm.taobao.org on the command line`
npm install -g hexo-cli

# Check whether hexo was installed successfully and view the version
hexo -v

After the installation is successful, we can enter hexo help on the command line to see how to use it (described in English, the author of the example part translates it into Chinese):

Usage: hexo <command>

command description
help Get help with commands
init Create a new Hexo folder
version display version information

More information can be viewed using hexo help [command], such as:

hexo help init
# Usage: hexo init [destination]

# Description:
# Create a new Hexo folder in the specified path or current directory.

# Arguments (parameters):
#  destination folder path. If not specified, initialize in the current folder

# Options:
#  - no-clone copies files instead of cloning them from GitHub
#  - no-install skips npm dependency installation (default initialization automatically installs dependencies)

Global Options:

options description
--config Specify the configuration file instead of using the default _config.yml
--cwd Specify CWD
--debug Display all details in the terminal
--draft Display draft posts
--safe Disable all plug-ins and scripts
--silent Hide output on console

On the official website commands A complete explanation can be found.

Station building

On the terminal, we can see an init command that we can use to initialize the hexo project, but before we build the site, we need to decide where to store the blog source code.

I recommend using something like Microsoft's OneDrive Cloud folders like win10. You can whitewash its 5G cloud storage space. When you modify the file under device A, it will automatically synchronize to the cloud. After switching back to device B and logging in, it will automatically download data from the cloud, which is a convenient way.

However, it is worth noting that OneDrive is a foreign service after all, and for well-known reasons, it may need to be scientifically accessed to the Internet in order to use it. This method is only a problem of data backup and synchronization, and it will not affect the construction of the following without using it.

# If you are a unix system, you can use this command to view the current path
pwd
# /Users/anran/OneDrive

# Initialize folder named blog
hexo init blog
# INFO  Cloning hexo-starter https://github.com/hexojs/hexo-starter.git
# other install info ...

# Enter folder
cd blog

After installation, the directory is as follows:

.
-_config.yml
 - package.json (application dependent information)
- node_modules (dependency packages)
- scaffolds (template file)
- source (resource folder is where user resources are stored)
| -_drafts
 | -_posts (list of articles/posts source code)
themes

To configure

We need it after the station is built. To configure There are two main configurations in hexo. One is the site configuration file with the path /_config.yml. The other is the theme configuration file, the path is / themes /(downloaded theme)/_config.yml.

We can first modify the following basic options in the site configuration file:

# Hexo Configuration

# Website Main Title, One of the Elements of SEO
title: blog

#Subtitle, optional
subtitle:

# Site Description, one of the elements of SEO, is used to tell search engines about the description of the site.
description: Sharing Life, Sharing Technology

# Key words of the website, such as:
keywords: Front end

# Website Author
author: anran758

# Because Hexo has a multilingual configuration and defaults to English, we need to modify the language back to Chinese.
language: zh-CN

start-up

After initializing the project, the relevant dependencies are installed by default, and then the blog is run by typing the following commands on the command line:

# Start the service, the default port is 4000. After starting the service, you can enter `http://localhost:4000'in the browser to see the effect.
hexo server

# or abbreviation
hexo s

# You can also use - p to specify port 9000
hexo s -p 9000

Writing steps

We usually operate blogs from the command line:

For example, the way to create an article is as follows: hexo new [layout] < title >

Hexo defaults to three layouts: post, page and draft, which correspond to different paths. We can also customize the layout, but the actual page will be the same as the post and will be stored in the source/_posts folder.

According to my own writing habits, the usual writing steps are:

  1. Create drafts
  2. Write on a draft
  3. Organize the details and view the results on the local server
  4. Published to a formal post
  5. Generate static files and deploy them (follow-up)

Create drafts

$ hexo new draft "My first post"
# INFO  Created: ~/blog/source/_drafts/My-first-post.md

A draft folder named _drafts is generated when the first draft is created. Then under the folder is a markdown file named My-first-post.md, which we just created. The contents of the file are as follows:

---
title: My first post
tags:
---

View drafts on the local server

We can start the local server and preview while writing, but by default the draft will not be displayed. If you want to view the draft, you can enter the following command:

$ hexo s -p 9000 --draft
# INFO  Start processing
# INFO  Hexo is running at http://localhost:9000 . Press Ctrl+C to stop.

# If you need to exit the server, hold down control + c

Publish draft

If we finish the details of the draft on the local server Colonel team, we can publish the draft as an article, otherwise it will not be packaged when we generate the static file of the blog:

# hexo publish [layout] <filename>
# Publish the draft as an article
$ hexo publish post My-first-post
# INFO  Published: ~/blog/source/_posts/My-first-post.md

After entering the command, you can see that the published articles are transferred to source/_posts/, thus completing the local article publication.

Generate static files

One of the tasks of the Hexo framework is to generate the source file markdown into HTML:

# Generate files
$ hexo generate
# INFO  Start processing
# INFO  Files loaded in 275 ms
# INFO  Generated: 2019/08/11/My-first-post/index.html
# INFO  1 files generated in 152 ms

# Short form
$ hexo g

# Monitor file changes and generate static files
$ hexo g --watch

# Generate files and deploy them (explained in separate chapters after deployment)
$ hexo g -d

theme

After we are familiar with the operation of the blog system, the next step is to beautify the blog. Hexo supports themes, and we can base it on Creating Theme Tutorial for Official Website Design by yourself, or directly in Theme Mall Find ready-made themes. Here take the theme Next recommended by the author as an example:


When I first used the next theme, the version was only 5.x, and there were still a lot of things needed for blogs that were not integrated. Looking back now, it turns out that Next has upgraded several large versions. The GitHub theme repository has also been migrated to https://github.com/theme-next, and even documents have two different versions.

New Documents It is built with a scheme of its own theme. It is an English-language document, which can ensure that the information is up-to-date. Old Documents The layout is easy to read, and it is also a Chinese document. Most parameters can be found in the document, but after all, there is no more maintenance. It is suggested that the latest document be used as a reference.

Installation topics can be cloned to blog/theme/below through git clone:

$ pwd
# /Users/anran/OneDrive/Blog

# Clear the cache and deployed files before starting the theme
$ hexo clean

# clone theme
$ git clone https://github.com/iissnan/hexo-theme-next themes/next

Then start theme in the site configuration file (/_config.yml). Open the theme profile (/themes/next/_config.yml) and select Scheme:

# _config.yml
- theme: landscape
+ theme: next

# /themes/next/_config.yml
# Provide three modes
#scheme: Muse
#scheme: Mist
scheme: Pisces

Some functional configurations, such as comments, subscriptions, data statistics, and SEO, have been integrated into the next theme configuration, but most of them require additional dependencies and need to be based on File To configure. next integrates in thematic configuration, because there are too many configuration customizations, readers can add corresponding statistics according to their own needs, and app key s related to SEO will not be further discussed.

deploy

We use git for deployment. We can deploy our website to a private server or to free github pages. This article describes how to deploy to github. If you don't have a GitHub account, you need to start withRegister an account.

The steps are as follows:

  1. Visit github.com and click sign up to register.
  2. Enter the registration page, enter the account password and mailbox, enter the verification code!

  3. Choose Free Users

  4. Next comes a survey of github recommendation services, which you can skip, of course.

  5. After verification, it will prompt you to create a repository. Here we will create a blog first.

  6. copy the warehouse link to the site configuration file (/_config.yml). Install the dependencies of hexo-deployer-git at the same time:

    npm install hexo-deployer-git --save
    url: https://yourname.github.io/blog # changed to github io address
    root: /blog/                           # To map resources to warehouse names
    
    deploy:
      type: git
      repo: https://Github.com/yourname/blog.git git address of Blog
      branch: gh-pages                            # Published to the gp-pages branch, if it does not exist, it is automatically created
  7. Then deployment begins. If you haven't configured the git account, it will prompt you to enter the account password, enter the correct account password and deploy successfully.

    # Or use `hexo d-g', both of which are equivalent effects
    hexo g -d
    
    # *** Please tell me who you are.
    
    # Run
    #  git config --global user.email "you@example.com"
    #  git config --global user.name "Your Name"
    
    # to set your account's default identity.
    # Omit --global to set the identity only in this repository.
    
    # fatal: unable to auto-detect email address (got '29625@DESKTOP-0R7P8H4.(none)')
    # Logon failed, use ctrl+c to cancel basic credential prompt.
    # Username for 'https://github.com': anran758
    INFO  Start processing
    INFO  Files loaded in 621 ms
    INFO  0 files generated in 424 ms
    INFO  Deploying: git
    INFO  Clearing .deploy_git folder...
    INFO  Copying files from public folder...
    INFO  Copying files from extend dirs...
    
    INFO  Congratulations! Your are using the latest version of theme NexT.
    Enumerating objects: 131, done.
    Counting objects: 100% (131/131), done.
    Delta compression using up to 8 threads
    Compressing objects: 100% (91/91), done.
    Writing objects: 100% (131/131), 257.72 KiB | 2.48 MiB/s, done.
    Total 131 (delta 43), reused 0 (delta 0)
    remote: Resolving deltas: 100% (43/43), done.
    To https://github.com/yourname/blog.git
     [new branch]      HEAD -> gh-pages
    Branch 'master' set up to track remote branch 'gh-pages' from 'https://github.com/yourname/blog.git'.
    
    # If you don't have a global git account, you can configure it first. Otherwise, you will be prompted to enter your account password in the next deployment.
    git config --global user.email "you@example.com"
    git config --global user.name "Your Name"
  8. Then we enter the settings item under the blog we created, and set github pages to gh-pages, which is the branch we set in the configuration before. So we can check our deployment online.~

Optimization and Extension

The following is a brief introduction to the related issues and extensions that are not mentioned in the document.

Local Search

next has built-in local search configurations, but the documentation indicates that additional hexo-generator-searchdb dependencies need to be installed. However, the project has now been archived and there are still some problems that have not been repaired. You can use it. hexo-generator-search To replace it. The recipient adds the following configuration to the site profile:

# Expansion: hexo-generator-search
# Search this site
# https://github.com/wzpan/hexo-generator-search
search:
  path: search.xml
  field: post
  format: html
  limit: 10000

When using the local search function, you may encounter the following errors:

This page contains the following errors:
error on line 86 at column 35: Input is not proper UTF-8, indicate encoding !
Bytes: 0x08 0xE8 0xB7 0x9F
Below is a rendering of the page up to the first error.

Most of the reasons for this error are due to the special string brought by Sogou input method. We can replace it in the source code. Open the editor (such as vscode) and replace the first byte / x08 of the global search error message Bytes with empty.

github emoji

If you want to support emoji in your blog, you can install it hexo-filter-github-emojis

# Use Github Emojis
# Docs: https://github.com/crimx/hexo-filter-github-emojis
githubEmojis:
  enable: true
  className: github-emoji
  unicode: false
  styles:
  localEmojis:

sitemap

In order for search engines to find our website, I also need to provide site map files to search engine spiders.

# hexo sitemap Generator and Baidu sitemap Generator
npm install hexo-generator-sitemap hexo-generator-baidu-sitemap --save

Add the following configuration to the site configuration file after the installation of dependencies:

# Expansion: hexo-generator-sitemap
# generate sitemap.
# https://github.com/hexojs/hexo-generator-sitemap
sitemap:
  path: sitemap.xml

# Expansion: hexo-generator-baidu-sitemap
# For Baidu's optimized sitemap, the author suggests that it would be better to submit it it manually to Baidu.
# https://github.com/coneycode/hexo-generator-baidu-sitemap
baidusitemap:
  path: baidusitemap.xml

Setting Page-Free Archives

If you want to load all the archive directories on one page, you can add the following configuration:

# hexo-generator-archive
# The plug-in is built into hexo by default, and only need to refer to the documentation to add configuration.
# https://github.com/hexojs/hexo-generator-archive
archive_generator:
  per_page: 0

Introduction of Pictures

There are two main ways to use pictures in hexo:

  • Introduce locally through resource folders
  • Using Graphic Bed

With the introduction of local resources, the configuration of _config.yml needs to be modified:

post_asset_folder: true

After setting the options, a folder with the same name will be generated every time you use hexo new [layout] < Title >. Then you can use the`
{% asset_img slug [title]%} ` to introduce image resources:

<! - For example, by inserting a banner graph, hexo automatically finds files in folders with the same name - >
{% asset_img banner.png banner %}

Here is an example.

The disadvantage of this approach is that it takes up local resources. If you deploy with git, it makes the. git file larger (even if the file is deleted, it will still exist in Git commit information).

The second way is to use the map bed. The problem with the free map bed is that the service may be unstable, the risk is not controlled by itself, and it is relatively less insured. But it can save space and even download faster in network transmission. If you use a drawing bed, you can try it. Sina Weibo Mapbed The plug-in can be downloaded to chrome and uploaded to the corresponding url after login.

README

By default, deploying source code generation to the server will overwrite the data generated last time. If you want to keep a README.md on github for the reader to see the instructions, you can set it up by _config.yml:

skip_render: ['images/loading.gif', 'README.md']

Topics: Programming github git npm xml