How to setup PrismJS and Autoloader plugin with Nuxt 3?
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 人喜欢
There is no comment, let's add the first one.