Add Prism.js using Vite

Introduction

PrismJS is a lightweight, extensible syntax highlighter that is used to highlight code snippets on web pages. It supports a wide range of languages and themes, and is easy to use and customize.

It's what I use on this blog when I want to highlight code snippets. I wanted to use this on a new project that uses Vite, so I decided to write this guide to help others do the same.

Installation

To add PrismJS to your Vite project, you need to install the prismjs package and the @types/prismjs package for TypeScript support.

npm install prismjs @types/prismjs

You also want to install the Vite Prism Plugin to make it easier to use PrismJS with Vite.

npm install vite-plugin-prismjs

Vite Configuration

Next, you need to configure Vite to use the Prism Plugin. You can do this by adding the following code to your vite.config.ts file:

import { defineConfig } from 'vite';
import prism from 'vite-plugin-prismjs';

export default defineConfig({
  plugins: [
    prism({
      languages: ['javascript', 'css', 'html', 'typescript'],
      plugins: ['line-numbers'],
      theme: 'tomorrow',
      css: true,
    }),
  ],
});

This code configures the Prism Plugin to use the tomorrow theme and the line-numbers plugin. You can customize this to suit your needs.

Usage

To use PrismJS in your project, you need to import the CSS file and the JavaScript file in your entry file. You can do this by adding the following code to your main.ts or main.js file:

import 'prismjs/themes/prism-tomorrow.css';
import 'prismjs/plugins/line-numbers/prism-line-numbers.css';
import 'prismjs';

This code imports the tomorrow theme and the line-numbers plugin CSS files, as well as the PrismJS JavaScript file.

You can now use PrismJS to highlight code snippets in your project. For example, you can use the following code to highlight a code block:

<pre><code class="language-javascript">
const greeting = 'Hello, World!';
console.log(greeting);
</code></pre>

This will highlight the JavaScript code block with the tomorrow theme and line numbers.

Resources

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring