babel-plugin-syntax-highlight
v4.0.0
Published
A Babel plugin that transforms the code contents of template literals lead by comments specifying a Prism.js language into syntax highlighted HTML.
Maintainers
Readme
babel-plugin-syntax-highlight
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.
Installation
To install babel-plugin-syntax-highlight with npm, run:
npm install babel-plugin-syntax-highlight --save-devConfigure Babel to use the plugin:
{
"plugins": ["syntax-highlight"]
}Examples
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.
A React component can be used display highlighted code with appropriate HTML and styles:
function SyntaxHighlightedCode({ language, code }) {
return (
<pre className={`language-${language}`}>
<code
className={`language-${language}`}
dangerouslySetInnerHTML={{ __html: code }}
/>
</pre>
);
}const syntaxHighlightedCode = (
<SyntaxHighlightedCode language="css" code={highlighted} />
);Requirements
Supported runtime environments:
- Node.js versions
^14.17.0 || ^16.0.0 || >= 18.0.0.
Projects must configure TypeScript to use types from the modules that have a // @ts-check comment:
compilerOptions.allowJsshould betrue.compilerOptions.maxNodeModuleJsDepthshould be reasonably large, e.g.10.compilerOptions.moduleshould be"node16"or"nodenext".
Exports
The npm package babel-plugin-syntax-highlight features optimal JavaScript module design. These CommonJS modules are exported via the package.json field exports:
