npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-shiki

v0.1.2

Published

Syntax highlighter component for react using shiki

Downloads

30

Readme

[!WARNING] This package is still a work in progress, it is not yet recommended for production use. Contributions are welcome! My goal is to eventually build this out as a near-drop-in replacement for react-syntax-highlighter

🎨 react-shiki

Syntax highlighting component and hook for react using Shiki

See the demo page for a version of this README with highlighted code blocks showcasing several Shiki themes!

Features

  • 🖼️ Provides a ShikiHighlighter component for highlighting code as children, as well as a useShikiHighlighter hook for more flexibility
  • 🔐 No dangerouslySetInnerHTML, output from Shiki is parsed using html-react-parser
  • 📦 Supports all Shiki languages and themes
  • 📚 Includes minimal default styles for code blocks
  • 🚀 Shiki dynamically imports only the languages and themes used on a page, optimizing for performance
  • 🖥️ ShikiHighlighter component displays a language label for each code block when showLanguage is set to true (default)
  • 🎨 Users can customize the styling of the generated code blocks by passing a style object or a className

Installation

[pnpm|bun|yarn|npm] [add|install] react-shiki

Usage

You can use the ShikiHighlighter component, or the useShikiHighlighter hook to highlight code.

useShikiHighlighter is a hook that takes in the code to be highlighted, the language, and the theme, and returns the highlighted code as React elements. It's useful for users who want full control over the rendering of highlighted code.

const highlightedCode = useShikiHighlighter(code, language, theme);

The ShikiHighlighter component is imported in your project, with the code to be highlighted passed as it's children.

Shiki automatically handles dynamically importing only the languages and themes used on the page.

function CodeBlock() {
  return (
    <ShikiHighlighter language="jsx" theme="ayu-dark">
      {code.trim()}
    </ShikiHighlighter>
  );
}

The component accepts several props in addition to language and theme:

  • showLanguage: boolean - Shows the language name in the top right corner of the code block.
  • addDefaultStyles: boolean - Adds default styles (padding, overflow handling, and border-radius) to the code block.
  • as: string - The component to be rendered. Defaults to 'pre'.
  • className: string - Class name to be passed to the component.
  • style: object - Style object to be passed to the component.
function Houston() {
  return (
    <ShikiHighlighter
      language="jsx"
      theme="houston"
      showLanguage={false}
      addDefaultStyles={true}
      as="div"
      style={{
        textAlign: 'left',
      }}
    >
      {code.trim()}
    </ShikiHighlighter>
  );
}

It can also be used with react-markdown:

import type { ReactNode } from 'react';
import type { BundledLanguage } from 'shiki';
import ShikiHighlighter, { isInlineCode, type Element } from 'react-shiki';

interface CodeHighlightProps {
  className?: string | undefined;
  children?: ReactNode | undefined;
  node?: Element | undefined;
}

export const CodeHighlight = ({
  className,
  children,
  node,
  ...props
}: CodeHighlightProps): JSX.Element => {
  const match = className?.match(/language-(\w+)/);
  // TODO: remove need for consumer use of BundledLanguage from shiki
  const language = match ? (match[1] as BundledLanguage) : undefined;

  const isInline: boolean | undefined = node ? isInlineCode(node) : undefined;

  return !isInline ? (
    <ShikiHighlighter
      language={language as BundledLanguage}
      theme={'houston'}
      {...props}>
      {String(children)}
    </ShikiHighlighter>
  ) : (
    <code className={className} {...props}>
      {children}
    </code>
  );
};

Pass CodeHighlight to react-markdown as a code component:

import ReactMarkdown from 'react-markdown';
import { CodeHighlight } from './CodeHighlight';

<ReactMarkdown
  components={{
    code: CodeHighlight,
  }}
>
  {markdown}
</ReactMarkdown>

This works great for highlighting in realtime on the client, I use it for an LLM chatbot UI, it renders markdown and highlights code in memoized chat messages:

const RenderedMessage = React.memo(({ message }: { message: Message }) => (
  <div className={cn(messageStyles[message.role])}>
    <ReactMarkdown components={{ code: CodeHighlight }}>
      {message.content}
    </ReactMarkdown>
  </div>
));

export const ChatMessages = ({ messages }: { messages: Message[] }) => {
  return (
    <div className='space-y-4'>
      {messages.map((message) => (
        <RenderedMessage key={message.id} message={message} />
      ))}
    </div>
  );
};