VuePress Tutorial

VuePress Introduction

VuePress is an Vue-driven static site generation tool. VuePress consists of two parts: a minimalist static website generation tool for a Vue-driven theme system, and a default theme optimized for writing technical documentation. It was created to support the documentation needs of the Vue subproject.

Each page generated by VuePress has corresponding pre-rendered static HTML that provides excellent load performance and is SEO-friendly. However, after the page loads, Vue takes over the static content as a full single-page application (SPA). When the user is browsing the site, other pages can be loaded as needed.

VuePress – How it works

The introduction to the principle of operation. The VuePress site is actually a single-page application powered by Vue , Vue Router and webpack. If you’ve used Vue before, when you’re writing or developing custom themes (you can even use Vue DevTools to debug your custom theme!), you’ll fit into the familiar development experience!

During the build process, we create a server rendered version of the application and actually render the corresponding HTML by accessing each route. In this way by Nuxt of nuxt generate command and Gatsby inspired other projects.

Each markdown file is compiled into HTML using markdown-it and then processed as a template for the Vue component. This allows you to use Vue directly in the markdown file, which is very useful when you need to embed dynamic content.

VuePress Features

Concise priority

For the project structure centered on markdown, the most simplified configuration helps you focus on creation.

Vue driver

Enjoy the Vue + webpack development environment, use Vue components in markdown, and develop custom themes through Vue.

High performance

VuePress generates each page as pre-rendered static HTML, after each page is loaded, and then runs as a single-page application (SPA).

Key Features of VuePress

  • Built-in markdown extension optimized for technical documentation
  • Ability to take advantage of Vue code embedded in markdown files
  • Vue-driven custom theme system
  • Automatically generate Service Worker
  • Google Analytics integration
  • Git-based “recent update”
  • Multi-language support
  • A default theme includes:
    • Responsive layout
    • Optional home page
    • Simple, out-of-the-box, title-based search
    • Algolia search
    • Customizable navigation bar and sidebar
    • Automatically generated GitHub links and page edit links

Getting Started with VuePress

Compatibility considerations

VuePress requires Node.js >= 8.

Global Installation

If you just want to use VuePress casually, you can install it globally:

# Global installation
yarn global add vuepress # or npm install -g vuepress

# Create markdown file
echo '# Hello VuePress' > README.md

#Start writing documentation
vuepress dev

# Construct
vuepress build

Install VuePress in an existing project

If you want to maintain documentation in an existing project, you should install VuePress as a local dependency. This setting also allows you to use the CI or Netlify services to deploy automatically when pushed.

# Install as a local dependency
yarn add -D vuepress # or npm install -D vuepress

# Create docs Table of Contents
mkdir docs
# Create markdown file
echo '# Hello VuePress' > docs/README.md

Note: When installing VuePress into an existing project with webpack 3.x as a dependency, it is recommended to use Yarn instead of npm. Because in this case, Npm cannot generate the correct dependency tree.

Then, to package.json add some scripts script:

 {
 "scripts": {
   "docs:dev": "vuepress dev docs",
   "docs:build": "vuepress build docs"
 }
}

You can start writing the documentation now:

yarn docs:dev # or npm run docs:dev

To generate a static resource, run:

yarn docs:build # or npm run docs:build

By default, the build files located .vuepress/distin the file by .vuepress/config.js the dest configuration fields. The built files can be deployed to any static file server. About how to deploy to some common services, please refer to the Deployment Guide.

VuePress Configuration

VuePress Configuration file

Without any configuration, the page will be too simple and the user will not be able to browse the site easily. Want to customize your site, you first need to create a directory in the document .vuepress directory. This is where all VuePress-specific (VuePress-specific) files are placed. Your project structure may grow like this:

├─ docs
│  ├─ README.md
│  └─ .vuepress
│     └─ config.js
└─ package.json

The basic file for configuring a VuePress site is .vuepress/config.js where you export a JavaScript object:

module.exports = {
 title: 'Hello VuePress',
 description: 'Just playing around'
}

If the development server is up and running, you should see that the page now has a title title and a search box. VuePress comes with built-in header-based search functionality – it automatically creates a simple search index from the title h2 and h3 header tags of all pages.

Note: This search is to traverse each item of the pages array, take out the array of headers, where each item corresponds to the markdown title, the specific code to view the /lib/default-theme/SearchBox.vue suggestions function)

Consult the configuration reference for a complete list of options.

Alternative configuration format, You can also write configuration files in YAML( .vuepress/config.yml) or TOML( .vuepress/config.toml) format.

Theme configuration

The VuePress theme is responsible for all layout and interaction details of the site. VuePress comes with a default theme (which you see now) designed specifically for technical documentation. It exposes many options, allowing you to customize the navigation bar (navbar), sidebar (sidebar) and homepage (homepage).

If you want to develop custom themes, refer to the custom theme.

App Level Enhancements

Since VuePress Vue application is a standard application, so you can create a .vuepress/enhanceApp.js file to use application-level enhancements, if this file exists, the file will be imported into the application. The file should by export default deriving a hook function mode, it will receive a number of objects containing application-level value as a parameter. You can use this hook to install additional Vue plugins, register global components, or add extra routing hooks:

Export default ({
 Vue, // The Vue version currently used by the VuePress app
 Options, // options for root Vue instances
 Router, // routing instance of the application
 siteData // website metadata
}) => {
 // ... use application level enhancements
}

Static resource processing in VuePress

Relative URLs

All markdown files are compiled into the Vue component and processed by webpack, so you should prefer to reference any resource with a relative URL:

![An image](./image.png)

This will and * .vueway of functioning in the same template file. The resource through image url-loader and file-loader processed and copied to the appropriate position of the generated static build file.

In addition, you can use the ~prefix clear that this is a request webpack module, which will allow you to use aliases or webpack npm dependencies reference documents:

![Image from alias](~@alias/image.png)
![Image from dependency](~some-dependency/image.png

Aliases can webpack .vuepress/config.js in configure Webpack configuration.

E.g:
module.exports = {
 configureWebpack: {
   resolve: {
     alias: {
       '@alias': 'path/to/some/dir'
     }
   }
 }
}

Public File

Sometimes you may need to provide static resources that are not directly referenced in any markdown or theme component – for example, favicons and PWA icons. In this case, you can put them .vuepress/public in, and they will be copied to the root directory generated.

Base URL

If your site is deployed to a non-root URL, you need .vuepress/config.js to set the base options. For example, if you plan to deploy your site https://foo.github.io/bar/, you base should set it to “/bar/”(it should always start and end with a slash).

Use standard URL, if you want to .vuepress/publicquote the picture, you must use as /bar/image.png URL like this. However, if you decide to change base it one day , such a path is very fragile. To solve this problem, VuePress provides a built-in helper $withBase (injected into Vue’s prototype) that generates the correct path:

<img :src="$withBase('/foo.png')" alt="foo">

Note that you can use not only the above syntax in the theme component, but also the above syntax in the markdown file.

In addition, if you set up base, it will automatically stitched as a prefix .vuepress/config.js option for all static resources URL.

Markdown Extension in VuePress

Header Anchors

The title will automatically get the anchor link. You can use markdown.anchor options to configure render anchor.

Links – Internal links

Order .md or .html internal links at the end, it will be converted <router-link>, for single-page application (SPA) navigation.

Every subdirectory of a static website should contain one README.md. This file will be automatically converted to index.html.

Note:

In writing “links to a directory index.html when” a relative path and do not forget to use at the end of /a closed, otherwise you will get a 404. For example, use /config/ instead /config.

If you want to link to another markdown file, remember:

  1. Add backlinks .html or.md
  2. Make sure the case is correct, because path matching is case sensitive

Example

Given the following directory structure:

[Home](/) <!-- Send the README.md in the root directory to the user -->
[foo](/foo/) <!-- Send README.md in the foo directory to the user -->
[foo title anchor] (/foo/#heading) <!-- Jump to a specific anchor location in the README.md file in the foo directory -->
[foo - one](/foo/one.html) <!-- Append .html -->
[foo - two](/foo/two.md) <!-- or append .md -->

External links

External links are automatically set to target=”_blank” rel=”noopener noreferrer”:

You can customize the properties of external links by configuring config.markdown.externalLinks.

Use the Vue in Markdown

API Access Restrictions

Because VuePress application when generating static build file, the server will be rendered by Node.js, so any Vue usage must conform to write common code requirements. In short, to ensure that only beforeMounted or mounted access the browser-specific API / DOM API hook function.

If you are using a display or unfriendly components for SSR (for example, contains a custom command), you can wrap them in the built-in <ClientOnly> components:

<ClientOnly>
 <NonSSRFriendlyComponent/>
</ClientOnly>

Note that this does not solve the problem of some components or libraries trying to access the browser API when ** static importing – in order to use the code of the browser environment when importing, you need to hook in the appropriate lifecycle In functions, dynamically import them:

<script>
export default {
 mounted () {
   import('./lib-that-access-window-on-import').then(module => {
     // use code
   })
 }
}
</script>

Note: Theme components are also subject to browser API access restrictions

VuePress uses Vue single file components to customize the theme. To use a custom layout, create a directory in the document root .vuepress/theme directory, and then create a Layout.vue file:

.
└─ .vuepress
  └─ theme
     └─ Layout.vue

This is the same as developing a normal Vue application. It all depends on how you organize your theme.

Site and pages metadata

For docs each .md file, Layout the component will be invoked only once, and the metadata for the entire site and the specific pages will each be exposed to this.$site and this.$page attributes are injected into the application of each of the components inside.

This is the site of $site value:

{
 "title": "VuePress",
 "description": "Vue-powered Static Site Generator",
 "base": "/",
 "pages": [
   {
     "lastUpdated": 1524027677000,
     "path": "/",
     "title": "VuePress",
     "frontmatter": {}
   },
   ...
 ]
}

title, description And base the .vuepress/config.js copy from the respective field. pagesAn array of metadata objects containing each page, including its path, the page title ( either explicitly specified in the YAML front matter or inferred from the first title on the page), and any YAML frontmatter data in the file.

It is you are viewing this page $page to:

 {
 "lastUpdated": 1524847549000,
 "path": "/guide/custom-themes.html",
 "title": "Custom theme",
 "headers": [/* ... */],
 "frontmatter": {}
}

If the user .vuepress/config.js provided in themeConfig, it can also be used $site.themeConfig. You can use it to allow users to customize the behavior of the theme – for example, specifying categories and page order. Then, you can use these data to $site.pages be used together to build a dynamic navigation links.

Finally, do not forget this.$route and this.$router can also be used as part of Vue Router API’s.

Deployment

The following guidelines are based on several common assumptions:

  • The document is placed in the project docs directory;
  • Use the default build output location ( .vuepress/dist).
  • VuePress is installed in the project local dependencies and is configured with the following npm scripts:
{
 "scripts": {
   "docs:build": "vuepress build docs"
 }
}

GitHub page

  1. In the docs/.vuepress/config.js settings correct base.
  2. If you intend to deploy to https://<USERNAME>.github.io/,  you can skip this step, because base by default “/”.
  3. If you plan to deploy it https://<USERNAME>.github.io/<REPO>/ (that is, your repository address is https://github.com/<USERNAME>/<REPO>), set base to “/<REPO>/”.
  4. In your project, create a following of deploy.sh files (appropriate to highlight the comment line), and then run it to complete the deployment:
#!/usr/bin/env sh

# Terminate an error
Set -e

#Build npm run docs:build

# Enter the generated build folder
Cd docs/.vuepress/dist

# If you are deploying to a custom domain name

# echo 'www.example.com' > CNAME

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

#If you want to deploy to https://<USERNAME>.github.io
# git push -f [email protected]:<USERNAME>/<USERNAME>.github.io.git master

# If you want to deploy to
https://<USERNAME>.github.io/<REPO>
# git push -f [email protected]:<USERNAME>/<REPO>.git master:gh-pages

cd -

TIP:  You can set the script to run automatically each time you push the code in your CI.

GitLab page and GitLab CI

  1. In the docs/.vuepress/config.js settings correct base.
  2. If you intend to deploy to https://<USERNAME>.gitlab.io/, you can skip this step, because baseby default “/”.
  3. If you plan to deploy it https://<USERNAME or GROUP>.gitlab.io/<REPO>/ (that is, your repository address is https://gitlab.com/<USERNAME>/<REPO>), set base to “/<REPO>/”.
  4. In .vuepress/config.js set dest to public.
  5. Created in the root directory of your project named .gitlab-ci.yml file, whenever you commit changes, it will automatically help you build and deploy:
image: node:9.11.1

pages:
 cache:
   paths:
   - node_modules/

 script:
 - npm install
 - npm run docs:build
 artifacts:
   paths:
   - public
 only:
 - master

Netlify

  1. In Netlify, create a new project from GitHub with the following settings:
    1. Build command: npm run docs:build or yarn docs:build
    2. Publish directory: docs/.vuepress/dist
  2. Click the Deploy button!

Google Firebase

  1. Make sure you have firebase-tools installed .
  2. Created in the root directory of your project firebase.json and .firebaserc write the following:
firebase.json:
{
"hosting": {
  "public": "./docs/.vuepress/dist",
  "ignore": []
}
}


.firebaserc:
{
"projects": {
  "default": "<YOUR_FIREBASE_ID>"
}
}
  1. Execution yarn docs:buildor npm run docs:build after using the firebase deploy command to deploy.

Surge

  1. First install the surge first .
  2. Run yarn docs:buildor npm run docs:build.
  3. To deploy to surge, run the surge docs/.vuepress/dist command.

You can also surge docs/.vuepress/dist yourdomain.com be deployed to [custom domain name (https://surge.sh/help/adding-a-custom-domain).

Heroku

  1. First install the Heroku CLI .
  2. Create a Heroku account here .
  3. Run heroku login and fill your Heroku credentials:

heroku login

  1. In your project root directory, create a named static.json file, which has the following contents:
static.json:{
 "root": "./docs/.vuepress/dist"
}

This is the configuration of your project, please refer to heroku-buildpack-static for more information.

  1. Configure Heroku’s git remote repository:
# Version change
Git init
Git add .
Git commit -m "My site ready for deployment."

# Create a new heroku app with the specified name
Heroku apps:create example

#Set up a build package for a static site (buildpack)

heroku buildpacks:set https://github.com/heroku/heroku-buildpack-static.git
  1. Deploy your site
 #Publishing station
Git push heroku master

# Open a browser to open a browser to view the Dashboard version of Heroku CI
Heroku open

Related JavaScript Tutorials For Beginners

JavaScript Introduction Tutorials
Introduction to JavaScript
Javascript Code editors
Javascript Reference and Specifications
Javascript Developer Console
Javascript Basics
JavaScript Hello World.!
External JavaScript Files
JavaScript Code Structure
JavaScript Variables
Use Strict in JavaScript

Leave a Comment