Skip to content
A Babel plugin that transforms the code contents of template literals lead by comments specifying a Prism.js language into syntax highlighted HTML.
JavaScript
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.github
.editorconfig
.eslintrc.json
.gitattributes
.gitignore
.npmrc
.prettierignore
.prettierrc.json
changelog.md
index.js
package.json
readme.md
test.js

readme.md

babel-plugin-syntax-highlight

npm version CI status

A Babel plugin that transforms the code contents of template literals lead by comments specifying a Prism.js language into syntax highlighted HTML.

Build-time syntax highlighting advantages:

  • 🚀 No runtime JS to slow page loads.
  • 🖌 Less client rendering work.
  • 🎨 Beautiful code the instant the HTML and CSS loads.

Setup

To install from npm run:

npm install babel-plugin-syntax-highlight --save-dev

Configure Babel to use the plugin:

{ "plugins": ["syntax-highlight"] }

Usage

In a file transpiled by Babel, lead a template literal containing syntax to highlight with a comment containing syntax-highlight and a Prism.js language name:

const highlighted = /* syntax-highlight graphql */ `
  scalar Upload
`

The comment may be surrounded by others on the same or other lines for editor syntax highlighting, Prettier formatting, etc.

const highlighted =
  /* syntax-highlight graphql */
  /* GraphQL */ `
    scalar Upload
  `

A block or line comment may be used:

const highlighted =
  // syntax-highlight graphql
  `scalar Upload`

The plugin removes the comment (preserving surrounding comments) and transforms the template literal contents into HTML:

const highlighted = `<span class="token keyword">scalar</span> <span class="token class-name">Upload</span>`

Styling the HTML is up to you; there are many theme stylesheets available. Often themes require <pre> and <code> containers with appropriate language classes.

React

const SyntaxHighlightedCode = ({ language, code }) => (
  <pre className={`language-${language}`}>
    <code
      className={`language-${language}`}
      dangerouslySetInnerHTML={{ __html: code }}
    />
  </pre>
)

<SyntaxHighlightedCode language="css" code={highlighted} />

Support

  • Node.js v10+
You can’t perform that action at this time.