Tutorial: building markdown previewer with Vue and electron


Tutorial: building markdown previewer with Vue and electron

The latest trend that developers have to adapt to is to write a code base for multiple operating systems.

ElectronIs a JavaScript framework that allows you to create desktop applications with simple JavaScript and HTML, and convert websites into executable applications that take full advantage of all the features of windows, MAC or Linux operating systems.

VueIs a library designed for building interactive and progressive web applications. It provides data responsive components with simple and flexible APIs.

In this tutorial, we will step by step how to use Vue and electron to build a markdown preview application.


To continue with this tutorial, you need to have the following conditions:

  • Familiar with HTML, CSS and JavaScript (ES6 +)
  • Vs code or any code editor installed on the development computer
  • Basic knowledge of Vue

What will we build

We will build a desktop application that previews the markdown code. Basically, we will have a grid with two columns: one for the text editor and one for the preview.

The results will be as follows:

Tutorial: building markdown previewer with Vue and electron

Setting up Vue

Create a new vuejs application using the Vue cli. If Vue cli is not installed on your development computer, you can install it using the following command:

npm install -g @vue/cli

-gFlag will install it globally on your computer.

Next, create a new Vue application using the CLIvue createCommand followed by the project name.

The name of our application ismarkdown-previewerSo we can create it by running the following command:

vue create markdown-previewer

functionvue create markdown-previewerA new Vue application will be created, but first, you will be prompted with questions to set up the application.

Step 1

Tutorial: building markdown previewer with Vue and electron

choiceManually select featuresFunction, and then press enter, which allows you to explicitly select the libraries to include in the new project.

Step 2

Tutorial: building markdown previewer with Vue and electron

To select and control an item on the feature list, the mouse doesn’t work here, so when you want to select / cancel a feature, use the arrow to move up and down, and then press the space bar. choiceRouterBabelandLinter

Step 3

Tutorial: building markdown previewer with Vue and electron

We don’t use history mode, instead, we’ll use hash mode.

Step 4

Tutorial: building markdown previewer with Vue and electron

choiceESLint + standard config。 This is basically our linter configuration, and eslint helps you maintain patterns as you write code.

Step 5

Tutorial: building markdown previewer with Vue and electron

Click lint when saving. When you save the code, it runs lint on the code.

clickLint on saveWhen you save the code, it runs lint on the code.

Step 6

Tutorial: building markdown previewer with Vue and electron

choicepackage.json, we will store all project dependencies here.

Step 7

Tutorial: building markdown previewer with Vue and electron

inputYorN, depending on whether you want to save it as a preset, this saves you time completing all of these steps when creating a new Vue application.

Click enter to start building a new Vue application.

After creating the application, you should see the following on the terminal:

Tutorial: building markdown previewer with Vue and electron

To run the application, move to the project directory and runnpm run serve

cd markdown-previewer
code . && npm run serve

code .Command will open the project in vs code, but you are welcome to use any code editor you choose.

After compiling, the application will be in the port of the applicationhttp://localhost: output on the terminal running on 8080/.

Tutorial: building markdown previewer with Vue and electron

If accessed on a browserhttp://localhost: 8080 /, you should see the following.

Tutorial: building markdown previewer with Vue and electron

Now that we’ve started and run the Vue application, it’s time to addelectron-builderYes.

Add electronic builder

electronic-builderThe package helps you package and build distributable electron applications for MacOS, windows and Linux, with out of the box automatic update support.

To add this package to your application, use theVue addCommand, this cool feature of Vue cli automatically configures the package in the application.

To install the package, run the following command

vue add electron-builder

Next, you will be prompted to choose your preferred version. Select the latest version (9.0.0 at the time of writing) and press enter to continue.

After you run this command, you create a in the SRC directorybackground.jsDocuments. This is what electron does, and the main process creates desktop windows for the application.

installelectronic-builderAfter the bag, you will be inpackage.jsonSome new scripts were found in the file:

"electron:build": "vue-cli-service electron:build",
"electron:serve": "vue-cli-service electron:serve",
"postinstall": "electron-builder install-app-deps",
"postuninstall": "electron-builder install-app-deps"

useelectron:serveCommand to run the application.

npm run electron:serve

This will open the electron app on your desktop.

Tutorial: building markdown previewer with Vue and electron

Install bootstrap

The next step is to install bootstrap, which will help you set up the user interface faster.

usevue addCommand to install bootstrap. Remember,vue addThe command will be inmain.jsPackage registration is handled in the file. To install it, run the following command:

vue add bootstrap-vue bootstrap

The system will ask if you want to use itbabel。 inputy, and then press enter to continue.

Tutorial: building markdown previewer with Vue and electron

Now we can set up the user interface (UI).

Setting up the user interface

Before setting up the user interface, let’s sort it out.

First, replace with the following codecompoments/HelloWorldCode in.

    <div class="container-fluid">
      <div class="row text-light">
        <div class="col-md-6">
        <div class="col-md-6">
export default {
  name: "HelloWorld"

This is the basic grid system in bootstrapeslint-loaderYou should have encountered an error. To disable it, create onevue.config.jsFile and add the following.

module.exports = {
  lintOnSave: false

In order for these changes to take effect, you need to restart the server.

Now, let’s set up the code editor. For this, we will useAceSoftware package.

To install this package, open your terminal and enter the following.

npm install --save-dev vue2-ace-editor

Next, in theHelloWorld.vueDefined in the componentaceBag.

components: {
    editor: require("vue2-ace-editor")

You also have to define some states for the editor. For example, you need to define the location of all the state you need to define. In addition, you should usestateThe height of the Attribute Editor.

data() {
  return {
    content: "",
    height: window.innerHeight - 100

Now create a method to introduce all instances of the editor, such as language types, themes, and patterns.

methods: {
  editorInit() {
    editorInit() {

Now you can register the components in the template section.


The output shall be as follows:

Tutorial: building markdown previewer with Vue and electron

Our user interface needs more cleanup, let’s remove the Vue logo and add a part to the preview.

To remove the Vue logo, go toviews/Home.vueFile and replace the code with the following.

    <HelloWorld />
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";
export default {
  name: "Home",
  components: {

We also need to remove the navigation links at the top of the application and change the background color. Open the rootApp.vueComponent, and then replace the code with the following.

  <div id="app">
    <router-view />
body {
  background: #000000;
#app {
  font-family: helvetica;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  height: 100%;

The result of the change should be as follows:

Tutorial: building markdown previewer with Vue and electron

Now we can add our preview section. We’ll use a card to preview the tag.

In yourcomponents/HelloWorld.vueAdd a simple card to the template in the file.

<div class="col-md-6">
  <div class="card text-left p-2" :style="styleObject">{{content}}</div>

Then, define a state to save some styles of data.

styleObject: {
  height: window.innerHeight - 100 + "px",
  color: "black",
  overflowY: "auto"

Here, we’re going to add some dynamic styles to div, the class iscardThe height will always be the same as the height of the code editor.

Anything you type in the code editor will be displayed on the preview card.

Tutorial: building markdown previewer with Vue and electron

Implementation of markdown previewer

You can usev-htmlDirective converts the code base to an HTML previewer.

<div class="card text-left p-2" :style="styleObject" v-html="content"></div>

This converts the code in the editor to HTML.

Tutorial: building markdown previewer with Vue and electron

We will demonstrate how to implement the markdown previewer in two ways: simple and complex.

Complex methods need to write their own custom markdown instructions. The simple way is to simply install a package from your markdown code.

Let’s start with a complex approach.

Complex ways

It is a cumbersome process that we will use regular expressions to set our own custom Vue instructions for tags.

First, in thesrcCreate adirectiveDirectory, and then create oneencode.jsDocuments. You will write all the markdown configurations here.

Next, register markdown tomain.jsIn the file.

import decode from '@/directives/decode'
Vue.directive("decode", decode)

Set your markdown code. staybind()Method encapsulates a custom Vue instruction and passes an element as a param.

export default {
  bind: el => {

Now, you can use it on templatesv-decodeInstructions.

<div v-markdown :key="content" class="card text-left p-2" :style="styleObject">{{content}}</div>

Pass the content as a key whenever it appears on the editorkeyupEvent, the instruction logs the content to the console.

The next step is to start writing some regular expressions for markdown.

Create a customrulesArray to hold all regular expressions. Start with a simple head:

const rules = [
  [/^(?:######)\s*(.+?)[ \t]*$/gm, '<h6>$1</h6>'],

This simple rule will######Convert to HTML elements.

Let’s break down what happened here:

  • ^Declare the position of the beginning of the line
  • (?:######)And character######matching
  • \s*Match space characters
  • (.+?)Matches all characters except line terminators. One example is the line terminator, which marks the end of a line in an input character sequence
  • [\t]*Is a qualifier that matches between 0 and unlimited, and matches spaces or tabs
  • gReturn all matches
  • msend^and$Match start / end of each line

Now that we have regex for the element, we can do the same for other header elements by modifying the expression.

const rules = [
  [/^(?:######)\s*(.+?)[ \t]*$/gm, '<h6>$1</h6>'],
  [/^(?:#####)\s*(.+?)[ \t]*$/gm, '<h5>$1</h5>'],
  [/^(?:####)\s*(.+?)[ \t]*$/gm, '<h4>$1</h4>'],
  [/^(?:###)\s*(.+?)[ \t]*$/gm, '<h3>$1</h3>'],
  [/^(?:##)\s*(.+?)[ \t]*$/gm, '<h2>$1</h2>'],
  [/^(?:#)\s*(.+?)[ \t]*$/gm, '<h1>$1</h1>']

Here, we define a regular expression for all header elements. To use them, we have to loop and replace our custom input with rules that match the expression.

bind(el) {
    let content = el.textContent
    rules.forEach(([rule, template]) => {
      content = content.replace(rule, template);
    el.innerHTML = content

With this definition, we can use the header element in the editor.

Tutorial: building markdown previewer with Vue and electron

Let’s define some other simple rules.

  • List:[/^(?:-)\s*(.+?)[ \t]*$/gm, '<ul><li>$1</li></ul>’]
  • Block quote:[/^(?:>)\s*(.+?)[ \t]*$/gm, ' <blockquote>$1</blockquote>']

Writing all the expressions for our markdown can be confusing and time consuming. But it’s always good to understand what’s going on behind all the packages. This leads us to a simple way to implement markdown previewer.

Simple method

A simpler way is to install a software package to help you process the data.

We will usevue-directive-markdown。 To install it, open your terminal and run the following command.

npm install vue-directive-markdown --save-dev 

Next, in themain.jsRegister and configure it in the file so that it can be accessed globally in the application.

import VueDirectiveMarkdown from 'vue-directive-markdown'
Vue.directive('decode', VueDirectiveMarkdown)

You can do this by analyzing thev-decodeTo access it.

<div v-decode :key="content" class="card text-left p-2" :style="styleObject">{{content}}</div>

Finally, pass the content as a key so that you update it every time you type.


Understanding how to write custom instructions will really improve your Vue skills. We all have to adapt to the need to write a code base for the desktop and the web.

go toGitHubGet the complete source code.

Author: wisdom ekpot

The first official account is “front-end developer”. The first time to read the latest article, it will give priority to two days to publish new articles. Attention after the private message reply: big gift package, send a network of high-quality video course online disk materials, you can save a lot of money!
Tutorial: building markdown previewer with Vue and electron