Coder Social home page Coder Social logo

jasomimo / ngx-highlightjs Goto Github PK

View Code? Open in Web Editor NEW

This project forked from murhafsousli/ngx-highlightjs

0.0 0.0 0.0 3.38 MB

Angular syntax highlighting module

Home Page: https://ngx-highlight.netlify.com/

License: MIT License

JavaScript 8.27% TypeScript 67.71% CSS 7.30% HTML 10.13% SCSS 6.59%

ngx-highlightjs's Introduction

Angular Highlight.js

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

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


Table of Contents

Install with NPM

npm i ngx-highlightjs

Import HighlightModule in your app

import { HighlightModule, HIGHLIGHT_OPTIONS } from 'ngx-highlightjs';

@NgModule({
  imports: [
    HighlightModule
  ],
  providers: [
    {
      provide: HIGHLIGHT_OPTIONS,
      useValue: {
        fullLibraryLoader: () => import('highlight.js'),
      }
    }
  ],
})
export class AppModule { }

Note: This will add highlight.js library including all languages to your bundle.

To avoid import everything from highlight.js library, you should import each language you want to highlight manually.

Import only the core library and the needed highlighting languages

import { HighlightModule, HIGHLIGHT_OPTIONS } from 'ngx-highlightjs';
 
@NgModule({
  imports: [
    HighlightModule
  ],
  providers: [
    {
      provide: HIGHLIGHT_OPTIONS,
      useValue: {
        coreLibraryLoader: () => import('highlight.js/lib/core'),
        lineNumbersLoader: () => import('highlightjs-line-numbers.js'), // Optional, only if you want the line numbers
        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, and useful if you want to change the theme dynamically
      }
    }
  ],
})
export class AppModule { }

HighlightOptions API

Name Description
fullLibraryLoader A function that returns a promise that loads highlight.js full script
coreLibraryLoader A function that returns a promise that loads highlight.js core script
lineNumbersLoader A function that returns a promise that loads line-numbers script which adds line numbers to the highlight code
languages The set of languages to register
config Set highlight.js config, see configure-options
themePath The path to highlighting theme CSS file

NOTE: Since the update of [email protected], should use coreLibraryLoader: () => import('highlight.js/lib/core') instead of coreLibraryLoader: () => import('highlight.js/lib/highlight')

Import highlighting theme

In version >=6.1.0, A new way is available to load the theme dynamically! this is OPTIONAL, you can still use the traditional way.

Dynamic way

Set the theme path in the global config, this makes it possible to change the theme on the fly, which is useful if you have light and dark theme in your app.

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

If you want to import it from the app dist folder, then copy the themes you want to your assets directory, or you can just use a CDN link to the theme.

When switching between the app themes you need to call the setTheme(path) from the HighlightLoader service.

import { HighlightLoader } from 'ngx-highlightjs';

export class AppComponent {

  constructor(private hljsLoader: HighlightLoader) {
  }

  // Assume you have a callback function when your app theme is changed
  onAppThemeChange(appTheme: 'dark' | 'light') {
    this.hljsLoader.setTheme(appTheme === 'dark' ? 'assets/styles/solarized-dark.css' : 'assets/styles/solarized-light.css');
  }
}

You can still use the traditional way

Traditional way

To import highlight.js theme from the node_modules directory 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

Use highlight directive

The following line will highlight the given code and append it to the host element

<pre><code [highlight]="code"></code></pre>

Demo stackblitz

Options

Name Type Description
[highlight] 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
[lineNumbers] boolean A flag that indicates adding line numbers to highlighted code element
(highlighted) HighlightAutoResult Stream that emits the result object when element is highlighted

NOTE

In Angular 10, when building your project, you might get a warning WARNING in ... CommonJS or AMD dependencies can cause optimization bailouts.

To avoid this warning, add the following in your angular.json

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

Read more about CommonJS dependencies configuration

Plus package

In version >= 4, a new sub-package were added with the following features:

  • Highlight gists using gists API
  • Highlight code directly from URL

Usage

import { HighlightPlusModule } from 'ngx-highlightjs/plus';
 
@NgModule({
  imports: [
    HighlightPlusModule
  ]
})
export class AppModule {
}

Highlight a gist file

  1. Use [gist] directive with the gist id to get the response through the output (gistLoaded).
  2. Once (gistLoaded) emits, you will get access to the gist response.
  3. Use gistContent pipe to extract the file content from gist response using gist file name.

Example:

<pre [gist]="gistId" (gistLoaded)="gist = $event">
  <code [highlight]="gist | gistContent: 'main.js'"></code>
</pre>

Highlight all gist files

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

Example:

<ng-container [gist]="gistId" (gistLoaded)="gist = $event">
  <pre *ngFor="let file of gist?.files | keyvalue">
    <code [highlight]="gist | gistContent: file.key"></code>
  </pre>
</ng-container>

Highlight code from URL directly

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

Example:

<pre>
  <code [highlight]="codeUrl | codeFromUrl | async"></code>
</pre>

This project uses Angular CLI to build the package.

$ ng build ngx-highlightjs

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

Murhaf Sousli

ngx-highlightjs's People

Contributors

murhafsousli avatar dependabot[bot] avatar armoucar avatar manekinekko avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.