Gatsby Remark PrismJS Plugin

7.16.0 · active · verified Tue Apr 21

gatsby-remark-prismjs is a Gatsby plugin designed to add syntax highlighting to code blocks within Markdown files during the build process, leveraging the popular PrismJS library. It is currently at version 7.16.0 and is a core component of the Gatsby ecosystem, with its release and maintenance closely aligned with Gatsby's own development cycle. As an official Gatsby plugin, it is actively maintained. Its primary differentiator is performing syntax highlighting at build time, pre-rendering the highlighted code into static HTML. This approach eliminates the need for client-side JavaScript to process and highlight code, leading to improved perceived performance and a faster initial page load compared to client-side highlighting solutions. It offers extensive configuration for themes, line numbering, language aliases, and custom language definitions.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core setup for `gatsby-remark-prismjs` in `gatsby-config.js` as a child plugin of `gatsby-transformer-remark`. It includes options for line numbers, language aliases, and a custom language extension. It also shows the necessary CSS theme and plugin imports in `gatsby-browser.js` and provides example Markdown code blocks for testing.

/* In gatsby-config.js */
module.exports = {
  plugins: [
    {
      resolve: `gatsby-source-filesystem`,
      options: {
        name: `blog`,
        path: `${__dirname}/content/blog`,
      },
    },
    {
      resolve: `gatsby-transformer-remark`,
      options: {
        plugins: [
          {
            resolve: `gatsby-remark-prismjs`,
            options: {
              classPrefix: "language-",
              showLineNumbers: true,
              aliases: { js: "javascript", sh: "bash" },
              languageExtensions: [
                {
                  language: "customjs",
                  extend: "javascript",
                  definition: {
                    custom_keyword: /(customKeyword)/,
                  },
                },
              ],
            },
          },
        ],
      },
    },
  ],
}

/* In gatsby-browser.js */
require("prismjs/themes/prism-tomorrow.css")
require("prismjs/plugins/line-numbers/prism-line-numbers.css")

/* Example Markdown File (e.g., content/blog/my-post.md) */
```js
// JavaScript Example
const greeting = "Hello, Gatsby!";
console.log(greeting);
```

```customjs
// Custom JavaScript with customKeyword
function customFunction() {
  customKeyword console.log("This is a custom highlight.");
}
customFunction();
```

```bash {numberLines: true}
# Shell Example with line numbers
echo "Hello from Bash"
npm install
```

view raw JSON →