·

How to setup PrismJS and Autoloader plugin with Nuxt 3?

Published at 2024-06-26 10:40:11Viewed 462 times
Professional article
Please reprint with source link

In previous the article Mathjax loads slow. How to load local JS file with Nuxt?, we explain how to render math equations in Nuxt.js using local CDN. With local CDN, we could easily load many Javascript libraries without slowing down our page loading.

PrismJS is a light Javascript library that highlights the code blocks on your pages. In the ordinary way that setup PrismJS (see How to do syntax highlighting for code blocks in Nuxt?), you need to import the file of almost every language that you need to highlight. For example, to highlight Typescript, you need to add import "prismjs/components/prism-typescript".  This is absolutely troublesome.

However, PrismJS has multiple plugins that extends its functionality. The Autoloader plugin can automatically load the language you need, so you don't have to import the files of all your needed languages one by one.

The easiest way to load Autoloader plugin is to use CDN. In this article, we will use the same method, which we used to load Mathjax, to setup PrismJS together with its autoloader plugin in Nuxt 3.

1. First, download the source code of PrismJS from Github:

https://github.com/PrismJS/prism/archive/refs/tags/v1.29.0.zip.

Or you can download it with npm:

npm install prismjs

2. Next, move it into the public directory in your Nuxt project. The directory structure will look like the following:

Nuxt-app/
     node_modules
     pages
     ...
     public/
        prismjs

3. Finally, configure your nuxt.config.ts, which will look like the following:

  css: [
    "prismjs/themes/prism-tomorrow.css"
  ],
  app: {
    head: {
      link: [{ rel: "icon", type: "image/png", href: "/favicon.svg" }],
      script: [
        {
          src: "/prismjs/components/prism-core.min.js",
          tagPosition: "bodyClose",
        },
        {
          src: "/prismjs/plugins/autoloader/prism-autoloader.min.js",
          tagPosition: "bodyClose",
        },
    ]
}

Note that we must add tagPosition: "bodyClose", because the script tag is placed in body not head. Now, PrismJS will automatically load every language you need, and all you need to do is just calling highlightAll().

0 人喜欢

Comments

There is no comment, let's add the first one.

弦圈热门内容

Vertically aligning CSS :before and :after content

I am trying to centre the link with the image, but can't seem to move the content vertically in any way.<h4>More Information</h4> <a href="#" class="pdf">File Name</a>The icon is 22 x 22px.pdf { font-size: 12px; } .pdf:before { padding:0 5px 0 0; content: url(../img/icon/pdf_small.png); } .pdf:after { content: " ( .pdf )"; font-size: 10px; } .pdf:hover:after { color: #000; }

Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved