简体   繁体   中英

Client-side Prism.js with npm

I'm trying to use Prism.js syntax highlighter client-side as an npm dependency, instead of loading it from <script src="..."> tags. Here is the Prism reference in package.json

{
    "dependencies": {
        "prismjs": "^1.5.1"
    }
}

And the way I'm trying to use it in my code

import Prism from 'prismjs'
Prism.highlightAll();

This produces the following results:

  • Tokenizing works for basic languages (html, javascript...)
  • Tokenizing does not work for other specific languages (lua, handlebars...)
  • For all languages, syntax coloring isn't applied (css file doesn't seem loaded)

So I'm wondering

  • Are there other language-specific packages (like prismjs-handlebars for instance)?
  • Are there theme-specific packages (like prism-okaidia for instance) which would import the css?

--

TL;DR

How to load/use Prism.js client-side from npm instead of from script tags?

I eventually found the way to do this.

1. Add style-loader and css-loader to package.json

{
    "dependencies": {
        "style-loader": "^0.13.1",
        "css-loader": "^0.23.0",
        "prismjs": "^1.5.1"
    }
}

2. Load css files in webpack.config.js

module: {
    loaders: [
        {
            test: /\.css/,
            loader: 'style-loader!css-loader'
        }
    ]
}

3. Import desired files in the application

import Prism from 'prismjs'
import 'prismjs/themes/prism-okaidia.css'
import 'prismjs/components/prism-handlebars.min.js'
import 'prismjs/components/prism-lua.min.js'

Prism.highlightAll();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM