iTranslated by AI
Creating Code Blocks in GatsbyJS
In this article, we will customize the code blocks of a blog created with GatsbyJS.
Since they are currently plain text, we will implement syntax highlighting and style adjustments.
Step 1: Add prismjs plugins
yarn add gatsby-transformer-remark gatsby-remark-prismjs prismjs
yarn add gatsby-remark-prismjs-title
Add gatsby-remark-prismjs and gatsby-remark-prismjs-title.
Step 2: Add configuration
Add the configuration to /gatsby-config.js.
Note that this should be added to the plugins array under gatsby-transformer-remark, not the root plugins.
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
+ 'gatsby-remark-prismjs-title',
+ {
+ resolve: `gatsby-remark-prismjs`,
+ options: {
+ classPrefix: 'language-',
+ inlineCodeMarker: null,
+ aliases: {
+ js: 'javascript',
+ sh: 'bash',
+ },
+ showLineNumbers: false,
+ noInlineHighlight: false,
+ languageExtensions: [
+ {
+ language: 'superscript',
+ extend: 'javascript',
+ definition: { superscript_types: /(SuperType)/ },
+ insertBefore: {
+ function: { superscript_keywords: /(superif|superelse)/ },
+ },
+ },
+ ],
+ prompt: { user: 'root', host: 'localhost', global: false },
+ escapeEntities: {},
+ },
+ },
]
}
By using aliases, you can shorten it to js.
Furthermore, by adding the sample styles as described in each README, it now looks like this:

gatsby-remark-prismjs-title and gatsby-remark-code-titles
Both of these plugins insert a title immediately before the code block.
In the one I didn't use this time, gatsby-remark-code-titles, the title is inserted as a single div. I chose gatsby-remark-prismjs-title because it uses a div > span structure, which makes it easier to style.
Discussion