Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly use PrismJS and its typings with typescript / angular 2

I'm building a little app with angular-cli and I would like to use PrismJS but I can't get it work.

So basically I've created a vendor folder where I put my Prism's scripts and styles and load them in the index.html.

I also need to install type definitions in order to be able to compile my app :

npm i --save-dev @typings/prismjs

Then, I just have to call Prism.whatever() anywhere in my code but this doesn't work.

Even my IDE doesn't recognize the namespace Prism.

By checking the content of the definition (index.d.ts) I've seen that since version 1.6, it doesn't contain

declare var Prism : PrismJS.Prism;

anymore. There is just some export namespace Prism. So I was wondering if I have to import something since any declare is used.

It seems weird to me to import something from a definition file.

As I wanted to step over this, I've installed an older version of the definition (1.4.16) which contains

declare var Prism : PrismJS.Prism;

Now, my IDE (webstorm) is happy! It can recognize Prism. But when I try to compile, webpack still outputs an error:

Cannot find name 'Prism'

So my question is pretty basic: what have I forgotten?

Sorry for this obvious question.

Thanks!

like image 992
Armelias Avatar asked Dec 01 '22 11:12

Armelias


2 Answers

in angular-cli add prism.js like that:

"scripts": [
   "../node_modules/prismjs/prism.js"
],

after that, you can make typescript happy with

declare var Prism;

and use it like that

<code [innerHtml]="myCode"></code>

ngAfterViewInit() {
   const code = 'var data = 1;';
   this.myCode = Prism.highlight(code, Prism.languages.javascript);
}
like image 53
Julia Passynkova Avatar answered Dec 04 '22 02:12

Julia Passynkova


I think you have done -

  1. npm install prismjs -S
  2. npm install @types/prismjs -D

now you need to import it ithe n component as -

import * as prism from 'prismjs';

and then use prism.whatEverMethod() which prism js supports

like image 41
Rahul Singh Avatar answered Dec 04 '22 01:12

Rahul Singh