Web Development

How to Use Prism.js for Code Syntax Highlighting

- 2 min read

If you are writing a blog that contains code blocks, a syntax highlighter is essential. It makes your code look organized and easy to read. In this guide, I’ll explain how you can use Prism.js inside your project.

Why Use Prism.js?

Downloading Prism.js

If you are working on a complex project, you can use npm to install Prism.js:

npm install prismjs

However, for most projects, a manual setup is simpler and easier to manage.

Steps to Download Prism.js Manually:

  1. Visit the Prism.js download page.
  2. Select a theme of your choice.
  3. Choose the languages you need.
  4. Select any additional plugins if needed.
  5. Download the CSS and JS files.

Prism.js provides a modular approach, allowing you to include only what you need, keeping the file size minimal.

My Prismjs configs
My Prismjs configs

Adding Prism.js to Your Project

Once you’ve downloaded the required files, add them to your project:

<link rel="stylesheet" href="path-to/prism.css" />
<script src="path-to/prism.js"></script>

How to Use Prism.js

After adding the CSS and JS files, you can use Prism.js by adding a class to your <code> blocks. Example:

<code class="language-html">
  <i id="toggle_theme_button" aria-hidden="true" class=""></i>
</code>

Language Support

For different programming languages, use the appropriate class:

If you use an unsupported class or didn’t select a language when downloading Prism.js, the code block will not be highlighted properly.

Conclusion

Prism.js is a powerful and easy-to-use syntax highlighter that enhances the readability of your code snippets. By following these simple steps, you can quickly integrate it into your project.