Detalhes do pacote

ngx-highlightjs

MurhafSousli262.4kMIT14.0.1

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

angular, highlight, highlightjs, prism

readme (leia-me)

Angular Highlight.js

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({
  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({
  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({
  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({
  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({
  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({
  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

changelog (log de mudanças)

Changelog

14.0.0

Possible breaking changes

  • refactor: Prevent provideHighlightOptions from being accidentally referenced in @Component in a component injector, closes #309.

13.0.0

  • Upgrade to Angular 19.
  • refactor: Use afterRenderEffect instead of effect in the highlight directives.

12.0.0

  • Upgrade to Angular 18, closes #286.

11.0.1

  • fix: highlight.js dependency was removed in v11, closes #283.

11.0.0

  • Update to Angular 17.
  • feat: Add provideHighlightOptions function to easily override the default options.
  • feat: Add provideGistOptions function in the plus package to easily set gist id and secret into the HTTP requests.
  • feat: Add startFrom and singleLine inputs to lineNumbers directive, closes #274.
  • feat: Make codeFromUrl pipe supports loading of relative URLs, closes #224.
  • feat: Add highlight directive which uses a different function and provide different options, closes #275.
  • feat: Add lineNumbersOptions property to set the default line number options.
  • refactor: Rename the previous highlight directive to highlightAuto.
  • refactor: split line numbers functionality into its own directive.
  • refactor: Use highlight.js original interfaces.
  • enhance: Allow loading theme from global options if highlight.js was imported externally.

Breaking changes

  • The highlight directive now uses a different function from highlight.js which requires selecting a language.
  • The highlightAuto directive automatically detects the language and highlights the code.

10.0.0

  • feat: Migrate to Angular standalone components, closes #260 in cadcd11.
  • fix: Add line-numbers as a sub package, closes #234 in 7f8f551.
  • refactor: Update deprecated rxjs usage.

Breaking changes

  • When using HighlightPlusModule, you must have provideHttpClient() provided in your main.ts file in order to make the http requests work.
  • The line numbers plugin is now included within the package, the import path should point to the new sub-package ngx-highlightjs/line-numbers
    providers: [
    {
     provide: HIGHLIGHT_OPTIONS,
     useValue: {
       lineNumbersLoader: () => import('ngx-highlightjs/line-numbers')
     }
    }
    ]
    

9.0.0

  • Update to Angular 16.

8.0.0

  • Update to Angular 15.
  • Fix setTheme does not load theme if themePath was not specified in the configuration, closes #247 in 4a74d84.
  • Fix Angular Universal error, closes 243 in 8815a9e.
  • Make Angular Universal happy with setTheme function HighlightLoader service, in 0ed6508.
  • Make gist setter public, closes #242 in 3208b0d.

7.0.1

  • Add support for trusted types (CSP), in 125a55b.

7.0.0

6.1.3

  • fix typo: Angular async pipe return type is 'string|null' not 'string' as [highlight] expect, closes #209 in 277322f.

6.1.2

  • fix: check if options is defined in HighlightLoader service, closes #219 in cac55cb.
  • fix: Update deprecated usage of throwError in rxjs 7.

6.1.1

  • fix: RxJS peerDependency warning when installing the package, closes#205 in 87c8521.
  • fix: Passing empty string to [highlight] input should clear the highlighted content (test cases is added for that), closes #119 in 2d67fb3.

6.1.0

  • feat: Load highlighting theme dynamically, ability to switch between themes easily, closes #194 in 9422d29.

6.0.0

  • Upgrade library to Angular 13

5.0.0

  • Upgrade usage to highlight.js v11, you can find the breaking changes from the official page here.
  • Build the library with partial compilationMode.
  • feat: Add the missing functions from v11 in HighlightJS service.
  • Remove deprecated function in v11, such as initHighlighting(), highlightBlock(), fixMarkup() from HighlightJS service.

Breaking changes

  • refactor: (highlighted) output has been updated to highlight.js v11, the result object has a new interface HighlightAutoResult.
  • refactor: HighlightJS.configure(config) has been updated the config interface to highlight.js v11.

4.1.4

  • Upgrade to Angular 12
  • Set peer dependency of highlight.js to v10

    The library is still compatible with the new version of highlight.js v11 but the highlighting function will be deprecated in their next release

4.1.3

  • Upgrade to Angular 11
  • Build the library in strict mode

Breaking changes:

  • refactor: Highlight directive => function highlightElement(code: string, languages: string[]): the languages param is not optional anymore.

4.1.2

  • fix: codeFromUrl display error message in the console even though it works, closes #141 in d60dc10.

4.1.1

  • Upgrade project to Angular 10.
  • fix: Remove the default behavior of adding highlight.js to the bundle directory, closes #122 in 339ff18.
  • fix: Setting the highlighted code to empty string will not reflect the value change, closes #199 in 9ee1942.

4.1.0-beta

  • Upgrade to Angular 9 in #113.
  • fix: Remove warning when the package is installed in Angular 9 in 6d491be.

4.0.2

  • fix: use element.textContent to set the code before highlighting, closes #105 in 34afad7.

4.0.1

  • fix: Change r property name to relevance in HighlightResult interface, closes #84 in ce53661.
  • fix: Sanitize highlighted code before appending it to the DOM, closes #101 in 9afe6b6.
  • fix: Check if nativeElement.firstChildElement is not null before calling line numbers lib, in 494c976.

4.0.0

  • feat: Lazy-load hljs library, closes #89 in 8cdba13.
  • feat: Lazy-load languages scripts, in 952f33c.
  • feat: Gist directive, closes #90 in 8b4c8fc.
  • feat: Highlight code directly from URL, closes #91 in 5fa3c59.
  • feat: Line numbers, closes #35 in c19b878.
  • enhance: Move highlight.js package from peerDependencies to dependencies
  • fix: Check if [highlight] input got undefined value, closes #81 in f2b14bd.
  • fix: Add test files, closes #79 in 2913d05.

Breaking Changes

  • Since the core library highlight.js will be lazy-loaded, all hljs functions in HighlightJS will return observables to make sure the library is loaded before execution.
  • HighlightChildren directive has been deprecated.
  • The global options languages property NgScrollOptions.languages type has changed.
  • HighlightModule.forRoot() is deprecated, the highlight global options can be set using the injection token HIGHLIGHT_OPTIONS

3.0.3

  • fix(HighlightChildren): fix OnDestroy() error (Cannot read property 'disconnect' of undefined), closes #75 in 3379905.

3.0.2

  • fix(HighlightChildren): Highlight children not working inside [innerHtml], closes #67 in 969f3b3.

3.0.0

Breaking Changes

Version 3 is written from scratch, Please read the updated documentations.

2.1.4

  • fix(HighlightJS): load hljs theme only if hljs script is loaded automatically, closes #56 in 66d0688.

2.1.3

  • fix(HighlightJS): Fix initializing hljs configure and the function parameter interface hljs.configure(config: HighlightConfig).
  • refactor(HighlightJS): Inject DOCUMENT to access the document class, in 4ff6ceb.
  • enhance(HighlightJS): Access hljs from document.defaultView.
  • Add rxjs as peerDependency.

2.1.2

  • fix peerDependencies for Angular >= 6
  • refactor(HighlightJS): Provide HighlightJS using providedIn: 'root'

2.1.1

  • refactor(HighlightJS): Add types on parameters in hljs functions, fixed in #40

2.1.0

  • feat(HighlightJS): Expose HighlightJS service with original functions, closes #37 in 90a8e17.

2.0.2

  • fix(Build): fix AOT build error, closes #31 in 161b36

2.0.1

  • Upgrade to Angular 6, closes #28 in #30

1.4.1

  • Fix(HighlightDirective): highlight="all", Apply .hljs class on code elements only, closes #23

1.4.0

  • Feature(language input): an array of language names and aliases restricting auto detection to only these languages, closes #20.
  • Feature(hljs global config): set global config in HighlightModule.forRoot({ config: hljsConfig })).
  • Support the manual load of hljs script and styles.

1.3.0

  • Feature: Add (highlighted) output, a stream that emits higlight result, closes #16.

1.2.6

  • Refactor with RxJS pipe 5.5 style

1.2.3

  • Fix(HighlightService) Move InjectionToken to a seperate file, closes #11

1.2.2

  • No Changes, just an update for the build enviroment

1.2.1

  • fix(HighlightDirective): Use el.tagName.toLowerCase() to check for if the highlight element is type of <code>

1.2.0

  • Remove HighlightUmdModule and systemjs support
  • Refactir(HighlightModule)
  • Add [code] input

1.1.1

  • Improve performance
  • Fix load hljs script only once
  • Remove hlAuto and hlDelay inputs from HighlightDirective, but they are still usable in HighlightUmdDirective
  • Update HighlightModule parameter:

    before:

        HighlightModule.forRoot('monokai-sublime', 'assets/js/highlight-js');
    

    after

        HighlightModule.forRoot({
          theme: 'monokai-sublime',
          path: 'assets/js/highlight-js',
          auto: true
        });
    

1.0.0

  • feat(HighlightModule): Choose highlight theme and set library path
  • feat(Auto-load script)
  • feat(Auto-load theme)

0.0.1

  • Initial release