DEV Community

Linda
Linda

Posted on

Add code snippets using Gridsome Prism.js plugin

Code snippet

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
Enter fullscreen mode Exit fullscreen mode

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',
      ]
    }
  }
Enter fullscreen mode Exit fullscreen mode

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-",
                },
            ]
        ]
    }
Enter fullscreen mode Exit fullscreen mode

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");
Enter fullscreen mode Exit fullscreen mode
require("gridsome-plugin-remark-prismjs-all/themes/solarized.css");
Enter fullscreen mode Exit fullscreen mode
require("gridsome-plugin-remark-prismjs-all/themes/tomorrow.css");
Enter fullscreen mode Exit fullscreen mode

Add Code Snippet to file

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

Example 1



```js
  let number = 4;
  console.log(number);
```

 

Render

let number = 4;
console.log(number);
Enter fullscreen mode Exit fullscreen mode

Example 2



```css
  body {
    min-height: 100vh;
    background-color: transparent;
    line-height: 1.5;
  }
```

 

Render

body {
    min-height: 100vh;
    background-color: transparent;
    line-height: 1.5;
}
Enter fullscreen mode Exit fullscreen mode

Read other articles

Top comments (0)