Mastering the art of integrating PrismJS and its typings effectively in TypeScript and Angular 2

I'm putting together a small application using angular-cli and I am trying to integrate PrismJS but facing issues with making it function properly.

Essentially, I've set up a vendor directory where I have placed Prism's scripts and styles, loading them in the index.html.

Additionally, I need to include type definitions to ensure my app compiles correctly:

npm i --save-dev @typings/prismjs

After that, I should be able to call Prism.whatever() anywhere within my code, however, this is not working as expected.

Even my IDE is unable to identify the namespace Prism.

Upon inspecting the content of the definition file (index.d.ts), I noticed that starting from version 1.6, it no longer includes

declare var Prism : PrismJS.Prism;

Instead, there is just an export namespace Prism. This led me to question whether I need to import something since there are no declare statements present.

To address this, I decided to revert to an older version of the definition (1.4.16) which does include

declare var Prism : PrismJS.Prism;

Now, my IDE (webstorm) recognizes Prism. However, when attempting to compile, webpack still throws an error:

Cannot find name 'Prism'

My query is quite straightforward: what am I missing here?

Apologies for the seemingly obvious inquiry.

Thank you!

Answer №1

To integrate prism.js into your Angular project using angular-cli, follow these steps:

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

Next, ensure TypeScript recognizes Prism by adding the declaration:

declare var Prism;

You can then utilize Prism in your component like so:

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

ngAfterViewInit() {
   const code = 'var data = 1;';
   this.myCode = Prism.highlight(code, Prism.languages.javascript);
}

Answer №2

It seems like you've completed the following steps -

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

Next, you'll need to import it in the component as -

import * as prism from 'prismjs';

After that, you can utilize prism.whatEverMethod() which is supported by Prism.js

Answer №3

To enhance the existing solutions, it's possible to incorporate different languages in addition to the default ones. To start with, you need to set up Prism by running npm i prismjs.

Modify your angular.json file as follows:

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

Incorporate the required languages in your component:

import 'prismjs';
import 'prismjs/components/prism-css';
import 'prismjs/components/prism-javascript';
// ...you can import other languages too

declare var Prism: any;

Check out the list of available languages here.

Lastly, implement the code highlighting feature:

code: string = 'helloWorld() { console.log("hello world"); }';
languageIdentifier: string = 'typescript';

ngOnInit() {
    this.code = Prism.highlight(this.code, Prism.languages[this.languageIdentifier]);
}

Incorporate it in your template like this:

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

Answer №4

I attempted to use angular-prism and ng2-prism, but unfortunately did not have any success (perhaps it was my mistake?).

If you encounter the "Expression has changed after it was checked." error, consider placing the code inside ngAfterViewInit within a setTimeout function.

ngAfterViewInit() {
    setTimeout(() => {
       const code = 'var data = 1;';
       this.myCode = Prism.highlight(code, Prism.languages.javascript);
    }
}

In terms of displaying correctly in HTML, it is more accurate to do the following:

<pre><code [innerHtml]="myCode" class="language-csharp"></code></pre>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to deactivate keyup loopback in Angular 2?

Here is my form: <div *ngIf="formLabel" style="padding: 0 16px"> <md-input [(ngModel)]="label.Name" placeholder="Label name" style="width: 100%"> </md-input> </div> <md-list-item *ngFor="l ...

Adjusting the return type based on the relationships defined in a Prisma object

Is there a way to implement a function that takes a Prisma object and dynamically sets the return type based on the included relations? I am aiming to type versionWithRelations with properties like pages, variables, and actions, while versionWithoutRelati ...

Is it feasible to evaluate a Typescript method parameter decorator at request time in a nodejs+nestjs environment rather than just at build time?

Looking to simplify my handling of mongodb calls with and without transactions in a single service method by writing a decorator. This would help eliminate the repetition of code and make things more efficient. Key points for usage: • Service class has ...

Warning: Unhandled promise rejection detected

I'm encountering an issue with Promise.reject A warning message pops up: Unhandled promise rejection warning - version 1.1 is not released How should I go about resolving this warning? Your assistance is greatly appreciated public async retrieveVe ...

Tips for making Angular automatically generate the property in HTML when employing the bind feature

When using property binding in Angular, I noticed that the property is not created in the HTML unless I directly write the value in the code. For example, in a StackBlitz demonstration with a 'button' component that changes color based on the typ ...

The Exporting menu in AmCharts4 does not include the ability to export in CSV, XLSX, or JSON formats

Right now, I am working with AmCharts4 and my objective is to export chart data in various formats such as CSV, XLSX, and JSON. To implement this, I have included the following scripts in index.html: <script src="https://www.amcharts.com/lib/4/core.js" ...

What is the best way to transform an Observable array containing objects into an Observable that emits the data contained within those objects?

Encountering an error: Error: Type 'Observable<Country[]>' is not assignable to type 'Observable'. Type 'Country[]' is missing properties like name, tld, alpha2Code, alpha3Code and more.ts(2322 The issue might be due ...

Emphasize x-axis heading in a Highcharts graph

In my Highcharts bar graph, I am looking for a way to dynamically highlight the x-axis label of a specific bar based on an external event trigger. This event is not a standard click interaction within the Highcharts graph. Currently, I have been able to r ...

What methods can be used to test included content in Angular?

When testing an Angular component that includes transclusion slots utilizing <ng-content>, it becomes challenging to verify if the transcluded content is correctly placed within the component. For instance: // base-button.component.ts @Component({ ...

React Native: Dynamic Rendering based on Conditions

I am looking for a solution to dynamically add rows to my code based on the result of my data analysis. For example, if the number is 0, I want to add 1 row, if it's 1, then 1 row, if it's 2, then 2 rows, and so on. I have tried different approac ...

Utilizing a monorepo approach enables the inclusion of all *.d.ts files

Scenario: In our monorepo, we have 2 workspaces: foo and bar. foo contains the following files: src/file.ts src/@types/baz.d.ts The bar workspace is importing @monorepo/foo/src/file. While type-checking works for the foo workspace, it does not work fo ...

Transmit: Forwarding information back to the recipient

My goal is to send an Http Post request (Registration form) using Angular, have it processed in the API, and if any errors occur like Please enter a username..., I want to return an error message to the client. Below is the Angular code for reference. Than ...

Show blob file as a PDF document in a popup or dialog box using HTML and TypeScript

I am currently working on integrating TypeScript and HTML to showcase the result of a webservice call as a PDF in a popup/dialog within the same page. While I can successfully open the PDF in a new tab using the window.open(url) method, I'm encounter ...

What is the best way to perform an AJAX request in Typescript with JSON data?

Currently, I am delving into the realm of AJAX and encountering some hurdles when attempting to execute an AJAX request with parameters. Specifically, I am facing difficulties in sending JSON data: My approach involves utilizing Typescript in tandem with ...

I'm struggling to transfer information from my form to TypeScript in Angular

Currently, I am working on developing a fullstack application using Node.js and Angular (material UI). However, I have encountered an issue that I need help with. I am trying to figure out how to retrieve data from an Angular form for a small web resource ...

The validation for the email field in Bootstrap, specifically in Angular 5, is not functioning properly for the "Email is Required

As a newcomer to Angular, I am seeking assistance with validation in my Angular 5 application. Specifically, I need to validate user emails and only allow navigation to a new component when a valid email is entered upon clicking a button. While pattern va ...

Error: The TypeScript aliases defined in tsconfig.json cannot be located

Having trouble finding the user-defined paths in tsconfig.json – TypeScript keeps throwing errors... Tried resetting the entire project, using default ts configs, double-checked all settings, and made sure everything was up-to-date. But still no luck. H ...

What is the best way to perform unit testing on an Angular component that utilizes the Router?

While working in Angular 2.0.0, I encountered an issue when unit testing a component that utilizes Router. The error 'Supplied parameters do not match any signature of call target.' keeps appearing, with Visual Studio Code highlighting the new Ro ...

`It is important to note that in Tailwind CSS, `h-8` does not supersede `h-4

I developed an Icon component that looks like this: import { IconProp, library } from "@fortawesome/fontawesome-svg-core"; import { far } from "@fortawesome/free-regular-svg-icons"; import { fas } from "@fortawesome/free-solid-svg- ...

Utilizing Angular to automatically extract keys from nested objects in a response

In my Angular application, I am facing a challenge with accessing nested responses from the server. The data structure contains multiple responses within one parent object, and I am struggling to dig deeper into it. Here is the code snippet I have so far: ...