npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ngx-highlightjs

v12.0.0

Published

Instant code highlighting, auto-detect language, super easy to use.

Downloads

216,969

Readme

Demo Stackblitz npm tests codecov Downloads Monthly Downloads npm bundle size (minified + gzip) License

Instant code highlighting directives


Table of Contents

Installation

Install with NPM

npm i ngx-highlightjs

Usage

Use provideHighlightOptions to provide highlight.js options in app.config.ts

import { provideHighlightOptions } from 'ngx-highlightjs';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHighlightOptions({
      fullLibraryLoader: () => import('highlight.js')
    })
  ]
};

Note: This includes the entire Highlight.js library with all languages.

You can also opt to load only the core script and the necessary languages.

Importing Core Library and Languages

import { provideHighlightOptions } from 'ngx-highlightjs';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHighlightOptions({
      coreLibraryLoader: () => import('highlight.js/lib/core'),
      lineNumbersLoader: () => import('ngx-highlightjs/line-numbers'), // Optional, add line numbers if needed
      languages: {
        typescript: () => import('highlight.js/lib/languages/typescript'),
        css: () => import('highlight.js/lib/languages/css'),
        xml: () => import('highlight.js/lib/languages/xml')
      },
      themePath: 'path-to-theme.css' // Optional, useful for dynamic theme changes
    })
  ]
};

HighlightOptions API

| Name | Description | |--------------------|--------------------------------------------------------------------------------------------------------------------------------| | fullLibraryLoader | A function returning a promise to load the entire highlight.js script | | coreLibraryLoader | A function returning a promise to load the core highlight.js script | | lineNumbersLoader | A function returning a promise to load the lineNumbers script for adding line numbers | | languages | The languages to register with Highlight.js (Needed only if you opt to use coreLibraryLoader) | | config | Set Highlight.js configuration, see configure-options | | lineNumbersOptions | Set line numbers plugin options | | themePath | The path to the CSS file for the highlighting theme |

Import highlighting theme

Dynamic Approach

Set the theme path in the global configuration to enable dynamic theme changes:

 providers: [
  {
    provide: HIGHLIGHT_OPTIONS,
    useValue: {
      // ...
      themePath: 'assets/styles/solarized-dark.css'
    }
  }
]

Alternatively, import the theme from the app's distribution folder or use a CDN link.

When switching between app themes, call the setTheme(path) method from the HighlightLoader service.

import { HighlightLoader } from 'ngx-highlightjs';

export class AppComponent {

  private hljsLoader: HighlightLoader = inject(HighlightLoader);

  onAppThemeChange(appTheme: 'dark' | 'light') {
    this.hljsLoader.setTheme(appTheme === 'dark' ? 'assets/styles/solarized-dark.css' : 'assets/styles/solarized-light.css');
  }
}

Traditional Approach

In angular.json:

"styles": [
  "styles.css",
  "../node_modules/highlight.js/styles/github.css",
]

Or directly in src/style.scss:

@import 'highlight.js/styles/github.css';

List of all available themes from highlight.js

Highlight Directive Usage

To apply code highlighting, use the highlight directive. It requires setting the target language, with an optional feature to ignore illegal syntax.

import { Highlight } from 'ngx-highlightjs';

@Component({
  standalone: true,
  selector: 'app-root',
  template: `
    <pre><code [highlight]="code" language="html"></code></pre>
  `,
  imports: [Highlight]
})
export class AppComponent {
}

Options

| Name | Type | Description | |----------------------|-----------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------| | [highlight] | string | Code to highlight. | | [language] | string | Parameter must be present and specify the language name or alias of the grammar to be used for highlighting. | | [ignoreIllegals] | boolean | An optional parameter that when true forces highlighting to finish even in case of detecting illegal syntax for the language instead of throwing an exception. | | (highlighted) | HighlightResult | Stream that emits the result object when element is highlighted |

HighlightAuto Directive Usage

The highlightAuto directive works the same way but automatically detects the language to apply highlighting.

import { HighlightAuto } from 'ngx-highlightjs';

@Component({
  standalone: true,
  selector: 'app-root',
  template: `
    <pre><code [highlightAuto]="code"></code></pre>
  `,
  imports: [HighlightAuto]
})
export class AppComponent {
}

Options

| Name | Type | Description | |---------------------|---------------------|------------------------------------------------------------------------------------------------------------| | [highlightAuto] | string | Accept code string to highlight, default null | | [languages] | string[] | An array of language names and aliases restricting auto detection to only these languages, default: null | | (highlighted) | AutoHighlightResult | Stream that emits the result object when element is highlighted |

Line Numbers Directive Usage

The lineNumbers directive extends highlighted code with line numbers. It functions in conjunction with the highlight and highlightAuto directives.

import { HighlightAuto } from 'ngx-highlightjs';
import { HighlightLineNumbers } from 'ngx-highlightjs/line-numbers';

@Component({
  standalone: true,
  selector: 'app-root',
  template: `
    <pre><code [highlightAuto]="code" lineNumbers></code></pre>
  `,
  imports: [HighlightAuto, HighlightLineNumbers]
})
export class AppComponent {
}

Options

| Name | Type | Description | |------------------|---------|--------------------------------------------------------------| | [singleLine] | boolean | Enable plugin for code block with one line, default false. | | [startFrom] | number | Start numbering from a custom value, default 1. |

NOTE

During the project build process, you may encounter a warning stating WARNING in ... CommonJS or AMD dependencies can cause optimization bailouts.

To address this warning, include the following configuration in your angular.json file:

{
  "projects": {
    "project-name": {
      "architect": {
        "build": {
          "options": {
            "allowedCommonJsDependencies": [
              "highlight.js"
            ]
          }
        }
      }
    }
  }
}

Read more about CommonJS dependencies configuration

Plus package

This package provides the following features:

  • Utilizes the gists API to highlight code snippets directly from GitHub gists.
  • Supports direct code highlighting from URLs.

Usage

To integrate this addon into your project, ensure the presence of HttpClient by importing it into your main.ts file.

import { provideHttpClient } from '@angular/common/http';

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient()
  ]
};

Highlight a gist file

  1. Use [gist] directive, passing the gist ID as its attribute, to retrieve the response through the (gistLoaded) output event.
  2. Upon the emission of (gistLoaded), gain access to the gist response.
  3. Use gistContent pipe to extract the file's content from the gist response based on the specified file name.

Example:

import { HighlightPlusModule } from 'ngx-highlightjs';

@Component({
  standalone: true,
  selector: 'app-root',
  template: `
    <pre [gist]="gistId" (gistLoaded)="gist = $event">
      <code [highlight]="gist | gistContent: 'main.js'"></code>
    </pre>
  `,
  imports: [HighlightPlusModule]
})
export class AppComponent {
}

Highlight all gist files

To loop over gist?.files, use keyvalue pipe to pass file name into gistContent pipe.

To highlight all files within a gist, iterate through gist.files and utilize the keyvalue pipe to pass the file name into the gistContent pipe.

Example:

import { HighlightPlusModule } from 'ngx-highlightjs';

@Component({
  standalone: true,
  selector: 'app-root',
  template: `
    <ng-container [gist]="gistId" (gistLoaded)="gist = $event">
      @for (file of gist?.files | keyvalue; track file.key) {
        <pre><code [highlight]="gist | gistContent: file.key"></code></pre>
      }
    </ng-container>
  `,
  imports: [HighlightPlusModule, CommonModule]
})
export class AppComponent {
}

Highlight code from URL directly

Use the pipe codeFromUrl with the async pipe to get the code text from a raw URL.

Example:

import { HighlightPlusModule } from 'ngx-highlightjs';

@Component({
  standalone: true,
  selector: 'app-root',
  template: `
   <pre>
     <code [highlight]="codeUrl | codeFromUrl | async"></code>
   </pre>
  `,
  imports: [HighlightPlusModule, CommonModule]
})
export class AppComponent {
}

Providing Gist API secret (Optional)

The package offers the provideHighlightOptions function, allowing you to set your clientId and clientSecret for the gist HTTP requests. You can provide these options in your app.config.ts file as demonstrated below:

import { provideHttpClient } from '@angular/common/http';
import { provideHighlightOptions } from 'ngx-highlightjs/plus'

export const appConfig: ApplicationConfig = {
  providers: [
    provideHttpClient(),
    provideGistOptions({
      clientId: 'CLIENT_ID',
      clientSecret: 'CLIENT_SECRET'
    })
  ]
};

Issues

If you identify any errors in the library, or have an idea for an improvement, please open an issue.

Author

Murhaf Sousli

More plugins