Trying to implement syntax highlighting for code using deno / fresh along with highlight.js has been a bit challenging. The versions of deno/fresh/highlight.js as of August 7, 2024 have caused my attempts to fail.
My development environment is Windows 10 on PowerShell where I have Deno installed.
The steps I follow to create the project are:
- Navigate to the root folder: cd (...)/deno_apps
- Create a new project by running:
deno run -A -r https://fresh.deno.dev
- Name the project code_highlighter
- In response to "do you want to use a styling library?" answer yes / tailwind.css
- For the question "do you use Visual Studio Code?" answer no (I'm using notepad++) -> this creates the project
- Go into the project folder cd code_highlighter
- Download highlight.js npm install highlight.js -> the installation process completes.
- Edit code_highlighter/routes/index.ts as shown below (to display both the highlighted source code with colors and indentation, and the html string generated by highlight.js):
° Remember to uncomment the import statement for the default css style import from highlight.js
import { Head } from "$fresh/runtime.ts";
import hljs from 'highlight.js/lib/core';
import cpp from 'highlight.js/lib/languages/cpp';
//import 'highlight.js/styles/default.css';
const createMarkup = (htmlString) => {
return { __html: htmlString };
};
export default function Home() {
const codeTxt = '#include <iostream>\nint main() {}';
hljs.registerLanguage('cpp', cpp);
const highlightedCode = hljs.highlight(
codeTxt,
{ language: 'cpp' }
).value;
return (
<div>
<pre>
<code dangerouslySetInnerHTML={createMarkup(highlightedCode)}>
</code>
</pre>
<div>
{highlightedCode}
</div>
</div>
);
}
To start the application:
deno task start
The output displayed is:
#include <iostream>
int main() {}
<span class="hljs-meta">#<span class="hljs-keyword">include</span> <span class="hljs-string"><iostream></span></span> <span class="hljs-function"><span class="hljs-type">int</span> <span class="hljs-title">main</span><span class="hljs-params">()</span> </span>{}
Observations made include:
- The indentation appears correct
- Highlight.js seems to be adding tags and classes to the code
- No color or styling is visible, making it hard to pinpoint the issue.
When attempting to uncomment the import of the default style from highlight.js :
import 'highlight.js/styles/default.css';
An error is encountered in the PowerShell console:
Watcher File change detected! Restarting! error: Uncaught (in promise) TypeError: Expected ';', '}' or at file:///C:/Users/crill/data/temp/deno_apps/code_highlighter/node_modules/.deno/[email protected]/node_modules/highlight.js/styles/default.css:1:5
... Watcher Process failed. Restarting on file change...
This situation raises questions about what went wrong and how to enable colored syntax highlighting as intended.