Creative Bracket

Highlight.js–Get started in Dart

In this article we will look at the Highlight.js library and reproduce the examples in Dart using the js interop package. We will also learn about using Web Workers to run code highlighting. This will improve page performance when processing large chunks of code.

Setup

Install the Dart extension for VS Code. It allows Dart language support and debugging for Dart projects.

Once the extension is installed, open up the Command Palette by going to View > Command Palette. You can also use the keyboard shortcut Shift+Cmd+P on Mac and Ctrl+Shift+P on Windows.

Once opened search and select “Dart: New Project“.

Select the Bare-bones Web App and generate a web-simple project. Set a project/name and a directory to generate a project folder.

Uncomment the dependencies section of the pubspec.yaml file and add the js package:

dependencies:
  js: ^0.6.0

Save the file. The Dart extension should run the pub get command to update the dependencies in your project. If not open the terminal and run the command manually.


Here’s the interop file we created in the video.

// lib/src/interop.dart
@JS()
library highlight_interop;

import 'dart:html';
import 'package:js/js.dart';

@JS()
external HighlightInterface get hljs;

@JS()
class HighlightInterface {
  external void highlightBlock(Element block);
  external void configure(HlConfigOptions options);
  external HighlightAutoInterface highlightAuto(String snippet);
}

@JS()
@anonymous
class HlConfigOptions {
  external factory HlConfigOptions({bool useBr});
  external void set useBr(bool useBrVal);
}

@JS()
class HighlightAutoInterface {
  external get value;
}

I hope this was insightful and that you learnt something new today.

Further reading

  1. js package
  2. How to Use JavaScript libraries in your Dart applications
  3. highlight.js library

Sharing is caring 🤗

If you enjoyed reading this post, please share this through the various social buttons hovering on the left/top side of the screen ↖️⬆️. Also, check out and subscribe to my YouTube channel (hit the bell icon too) for videos on Dart.

Subscribe to the newsletter for my free 35-page Get started with Dart eBook and to be notified when new content is released.

Like, share and follow me 😍 for more content on Dart.

Jermaine Oppong

Hello 👋, I show programmers how to build full-stack web applications with the Dart SDK. I am passionate about teaching others, having received tremendous support on sites like dev.to and medium.com for my articles covering various aspects of the Dart language and ecosystem.

Useful learning materials