In this tutorial 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.
Watch full tutorial
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.