The original blog

Shoot the breeze

A long time ago, I had a static blog site built by Hexo: OX:. I remember it took a lot of effort to get it out: Anger: and then I changed some configuration and style on and off. But because I felt all kinds of trouble, I put it on Github and accumulated lots of dust: Cupid:, I don’t want to clean it anymore (actually I haven’t used it for a long time and I forgot how to use it :-1::poop:). I looked at the number of visits to the static website on Baidu and found out that no one had visited it in a long time. One sweat_smile: So I decided to go to bed (yes, it was a dead of night) and the next day set up a static blog with a simple framework to record what I see and think :tada: The next morning after lunch (sleep until noon :sunglasses), I read VuePress official website, yes, I chose VuePress frame, as for why, there are the following points:

1. Currently developing vUE framework: Fire: 2. Just want to make a vue framework: Muscle: 3.

What are its benefits, features, and comparisons to other frameworks? Look at somebody else’s official website. That’s good

Project structures,

Have no what to say of, according to somebody else official website take finish matter, somebody else write of so clear, clear. I feel the documents produced by The University of Utah are very friendly and easy to read

Install VuePress as a local dependency
yarn add -D vuepress NPM install -d vuepress

Create a new docs folder. You can also create it manually by opening the editor
mkdir docs

Create a new markDown file
echo '# Hello VuePress! ' > docs/README.md

-----but: This is not a good way to start, put package.json to save trouble, so finish the process when you feel it.
npx vuepress dev docs
Copy the code

After the project is installed, we go to package.json and add the script startup

 "scripts": {
    "docs:dev": "vuepress dev docs"."docs:build": "vuepress build docs"
  }
Copy the code

There are three things we need to know now:

1. All future articles will be written in Docs

2. Develop, that is, execute when writing:

yarn docs:dev # or: NPM run docs:dev // default port http://localhost:8080/
Copy the code

3, package generate static HTML file, execute

yarn docs:build NPM run docs:build
Copy the code

By default, the generated static files are stored in. Vuepress /dist, but that can be changed. Let’s start with the docs directory where we’ll be doing more:

.├ ─ docs // Create a new folder under this folder and then create the MD document. │ ├─ ├─ public │ ├─ general │ ├─ general │ ├─ general │ ├─ general │ ├─ general │ ├─ general │ ├─ general │ ├─ general │ ├ ─ └ config.js // ├ ─ ├ ─ package.json //Copy the code

Forgive me for this part of the rough, in fact, this part of the official website is good, someone else is really very detailed, to talk about the main content is the following:

Home page configuration

The default theme of the official website provides a page that can be generated by writing configuration only, and the format is fixed, which is exactly the same as the homepage of VuePress, but this is not what I want (I do not know what I want), so I created a new component called home in. VuePress/Components, and introduced it in the homepage: (MD file can write vUE code oh)

// Do not copy comments -- navbar: false // do not navigation bar isNoPage: true // custom attributes sidebar: false // do not side navigation pageClass: <home /> <home />Copy the code

. Vuepress/components/home. Vue and we usually write vue do not have what distinction, reference when it is ok to use the file filename, website introduction, because it is I have no idea what kind of home page to make it, so I put it the first isNoPage is written by myself, This.$site. frontMatter is a custom pageClass class, which will be added to the outer div when compiling, and can be used to write your own style

/** This section of CSS can be written in.vuepress/style.styl, this is the style I wrote for the first page **/
home-list{
  .page-edit{
    display: none /** Hide the edit and last modification time tags on the home page **/}#gitalk-container{
    display: None /** Hide comments on home page **/}}Copy the code

Implementation of the list page

For every article page, I add it in the header

Tags: Vuepress, front-endAccording to the website, VuePress consists of two parts: a minimalist static website generator that allows you to develop topics using Vue, and a default theme optimized for writing technical documents. It was created to support the documentation needs of Vue and its subprojects. ---
Copy the code
  • Tags: Are the tags of the current page, used to create a tag cloud on the list page
  • Description: Indicates the description of the page. It is displayed on the list page and can be obtained from the official websitemoreBefore themethodsBut it will have a style, so it will feel ugly, so I added this onedescriptionOf course, I did not give up the method of the official website, because sometimes I may really be too lazy to write description information, so I added a judgment
< div v - if = "item. The frontmatter. The description" class = "art" > {{item. Frontmatter. The description}}... <a :href="item.path" class="look"> </a> </div> <div class="art" V-html ="item. HTML "V-else >Copy the code

To get a list of articles, I set isNoPage at the beginning

const arts = this.$site.pages.filter(item= > {
  return! item.frontmatter || ! item.frontmatter.isNoPage })Copy the code

Implementation of tags

My TAB is a VUE component, and then I introduce a reshuffle in the list page; I’m going to start each post with tags, and I’m going to iterate through this.$site.pages in the tag component to get all the tags, and then untag all of my pages

<template> <div class="tags"> <h6> <span v-for="item in tags" @click="handleChangeTag(item)">{{item}}</span> <span @click="handleChangeTag('all')"> all </span> </div> </template> <script> export default {data() {return {tags: []}}, created() { const tags = this.$site.pages.map(item => { return item.frontmatter && item.frontmatter.tags || "" }) const tagsArr = tags.join(",").split(",").filter(i => i ! == "") this.tags = [...new Set(tagsArr)] }, methods: HandleChangeTag (tag) {this.$emit('change-tag',tag)}},} </script>Copy the code

Favorite. Icon configuration

Favorite. Icon is that little icon in the top left corner of a web page

So first we need a little icon, and then we put.vuepess/publicDown, then open.vuepress/config.jsTo add

head:[
	['link', { rel: 'shortcut icon'.href: '/favorite.icon type: 'image/jpg'}]]Copy the code

Note that the href is /favorite. Icon, not /public/favorite

Style changes

Create two new styl files under.vuepress to write styles

Override. Styl: Used to override the default body style. For example, IF I want my content to take up 90% of the screen, I can:

$contentWidth = 90%
Copy the code

Style. styl: Write your own custom styles in this folder, such as changing the color of the navigation separately

.navbar{
  background:red
}
Copy the code

The official website for this introduction

Modify the copy

Copyright information is displayed when we make a large text copy of the nuggets:

Build your own blog with Vuepress

Author: Tell me a joke link: juejin.cn/post/684490… The copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source.

So how do we implement this function in the blog? In fact, it is very simple, first modify our.vuepress/ enhanceapp.js file (enhanceapp.js introduction).

import copy from './common/copy'

export default ({
  Vue, // VuePress is using the Vue constructor
  options, // Some options to attach to the root instance
  router, // Route instance of the current application
  siteData // Site metadata= > {})setTimeout(() = > {
    try {
      document && (() = > { // The document is judged to prevent errors at compile time
        copy()
      })()
    } catch (e) {
      console.error(e.message)
    }
  },500)}Copy the code

Then create a new copy. Js file

export default() = > {function addCopy(e) {
    let copyTxt = ""
    e.preventDefault(); // Cancel the default replication event
    copyTxt = window.getSelection(0).toString()
    copyTxt = `${copyTxt}\n Author: Still waters run deep \n 译 文 :The ${window.location.href}\n Copyright belongs to the author. Commercial reprint please contact the author for authorization, non-commercial reprint please indicate the source. `
    const clipboardData = e.clipboardData || window.clipboardData
    clipboardData.setData('text', copyTxt);
  }
  document.addEventListener("cut".e= > {
    addCopy(e)
  });
  document.addEventListener("copy".e= > {
    addCopy(e)
  });
}
Copy the code

This can be achieved, you can go to the blog experience

Add comments

Star2: : I use GITALK for my comment system. The official website says it is a comment plugin developed based on Github Issue and Preact. It seems that valine and Gitment are widely used now, which seems to be able to count the amount of reading; I hope gitalk can also provide a reading statistics function, the official website provides two ways, one is to introduce JS files in HTML, the other is to use the form of NPM package, I choose to use JS to dynamically insert the JS and CSS required by the comments into the page, First modify the code in.vuepress/ enhanceapp.js:

import getGitalk from "./common/getGitalk"
import copy from './common/copy'

export default ({
  Vue, // VuePress is using the Vue constructor
  options, // Some options to attach to the root instance
  router, // Route instance of the current application
  siteData // Site metadata= > {})setTimeout(() = > {
    try {
      document && (() = > {
        getGitalk.call(this, siteData)
        copy()
      })()
    } catch (e) {
      console.error(e.message)
    }
  },500)}Copy the code

The implementation of getgitalk.js is as follows

export default ({pages})=> {
  const path = window.location.pathname
  // Get the current page information
  const dist = pages.filter(item= > {
    return item.path === path
  })[0]

  // Comments will only be displayed if isNoPage is false
  if(! dist.frontmatter || ! dist.frontmatter.isNoPage) {const page =document.querySelector('.page')

    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);

    scriptGitalk.onload= () = > {
      let gitalk = document.createElement('div')
      gitalk.id = 'gitalk-container'
      page.appendChild(gitalk)
      var _gitalk = new Gitalk({
        clientID: '11111111111111'.clientSecret: '2222222222222222'.repo: 'slbyml.github.io'.// The name of the repository where the comments are stored
        owner: 'slbyml'.admin: ['slbyml'].// There can be more than one administrator of the warehouse
        id: decodeURI(path),      // Generate an issue for each page based on the URL, ensuring that comments between pages are independent
      })
      _gitalk.render('gitalk-container')}}}Copy the code

forgitalkSee the official website for the usage of “, but there are two elementsclientSecretandclientSecretWhere did these two come from? YeahI applied here, you can see the two generated fields after the creationNote: If you want to include a third party framework in your framework, such as element-UI, you can also include registration in this JS :::

The deployment of

Change package.json->script:

"scripts": {
    "docs:dev": "vuepress dev docs"."docs:build": "vuepress build docs"."deploy": "bash deploy.sh"  // Static files are generated and uploaded to Github
  }
Copy the code

Then create the deploy.sh file in the root directory:

#! /usr/bin/env sh

Make sure the script throws any errors it encounters
set -e

Generate static files
npm run docs:build

Go to the generated folder
cd dist

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

Github. IO /
      
git push -f [email protected]:slbyml/blog.git master

cd -
Copy the code

My default generated static file is dist in the root directory, because I changed the configuration in config.js to keep the docs files clean

dest: 'dist'
Copy the code

The static file is automatically generated when NPM run deploy is executed and uploaded to Github

Static file upload CDN

Recently, I feel that the website loading JS and CSS is very slow, it takes one or two seconds, as a front-end, must think of ways to do optimization, the most convenient way is to upload static files on the CDN, I used to upload ali cloud; I put the configuration in the configureWebpack of.vuepess/config.js at the beginning. After successfully uploading the configuration, the package file app.hash.js was found on the page. At the beginning without feeling may be because the packaging file (window. WebpackJsonp = window. WebpackJsonp | | []), push ([[0], []]). ; We don’t know why we don’t have this, but the way to do it now is to upload in deploy.sh; Take my uploading ali Cloud as an example (qiniu and other CDN are the same); Install webpack-aliyun-oss; Then create an upload.js file in the root directory to hold the upload code

const WebpackAliyunOss = require('webpack-aliyun-oss');
new WebpackAliyunOss({
  from: './dist/assets'.dist: 'dist'.region: 'Aliyun upload area; Example: the oss - cn - Beijing '.deletOrigin: true.accessKeyId: 'your accessKeyId'.accessKeySecret: 'your accessKeySecret'.bucket: 'slbblog'.setOssPath: filePath= > {
    // some operations to filePath
    let index = filePath.lastIndexOf("dist");
    let Path = filePath.substring(index + 4, filePath.length);
    return Path.replace(/\\/g."/");
  },
  setHeaders(filePath) {
    // some operations to filePath
    return {
      'Cache-Control': 'max-age=31536000'
    }
  }
}).apply();
Copy the code

This file is then executed in deploy.sh

#! /usr/bin/env sh

Make sure the script throws any errors it encounters
set -e

Generate static files
npm run docs:build
# upload file
node './upload.js'

Go to the generated folder
cd dist

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

Github. IO /
      
git push -f [email protected]:slbyml/blog.git master
git push -f [email protected]:slbyml-01/slbyml.coding.me.git master 

cd -

Copy the code

Finally, the static file path referenced by the page is transposed to.vuepess/config.js of Ali Cloud

module.exports={
  // Omit other configurations
  configureWebpack: (config, isServer) = > {
    if (process.env.NODE_ENV === 'production') {
      // Change the address to your Aliyun address
      config.output.publicPath = '//slbblog.oss-cn-beijing.aliyuncs.com/dist/'}}}Copy the code

This is done, there is no problem with the test; Later static files can happily load CDN files, JS file loading time is reduced to ms level; In the end, these are all things I do myself and may have a better implementation, so welcome to discuss!! Clap: something you want to add in the future:

  • Added more drop-down loading features
  • Rich list page
  • Rich home page

Reproduced the original