Linda Ojo

Add code snippets using Gridsome Prism.js plugin

Published: 2020-12-21
preview-image

Code snippets are a key part of writing for any developer. In this post, I am going to walk you through a simple way to add code snippets to your posts.

Install plugin


install the prism.js plugin by running the command below in your terminal.

npm i gridsome-plugin-remark-prismjs-all

Add plugin in gridsome.config.js


// In your gridsome.config.js
transformers: {
    //Add markdown support to all file-system sources
    remark: { 
      externalLinksTarget: '_blank',
      externalLinksRel: ['nofollow', 'noopener', 'noreferrer'],
      anchorClassName: 'icon icon-link',
      plugins: [
        'gridsome-plugin-remark-prismjs-all',
      ]
    }
  }

You could set custom class names which you can use for styling as shown below

// In your gridsome.config.js
transformers: {
        plugins: [
            [
                "gridsome-plugin-remark-prismjs-all",
                {
                showLineNumber: true,
                highlightClassName: "gridsome-highlight",
                codeTitleClassName: "gridsome-code-title",
                classPrefix: "language-",
                },
            ]
        ]
    }

Add a theme in your main.js

There are 3 different themes presently available, you can import anyone as shown below

require("gridsome-plugin-remark-prismjs-all/themes/night-owl.css");
require("gridsome-plugin-remark-prismjs-all/themes/solarized.css");
require("gridsome-plugin-remark-prismjs-all/themes/tomorrow.css");

Add Code Snippet to file

Wrap your code in triple backquotes then specifying the code language and title. Check out some examples and their resulting renders below.

Example 1

```js{codeTitle: "Prism.js example1"}
    let number = 4;
    console.log(number);
``` 

Render

Prism.js example1
    let number = 4;
    console.log(number);

Example 2

```css{codeTitle: "Prism.js example2"}
body {
    min-height: 100vh;
    background-color: transparent;
    line-height: 1.5;
}
``` 

Render

Prism.js example2
body {
    min-height: 100vh;
    background-color: transparent;
    line-height: 1.5;
}

Subscribe to Newsletter

Be the first to know about quality articles and poems written by Linda Ojo.