"Despite having a fresh installation of Deno, the highlighting style in highlight.js

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">&lt;iostream&gt;</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.

Answer №1

Trying to import a .css file directly into a TypeScript file is a recipe for disaster. The TypeScript compiler will likely throw errors and cause chaos.

To work around this issue, I found success using the npm package mentioned below:

https://github.com/GeoffSelby/tailwind-highlightjs

Just be aware that you may need to modify the tailwind.config.ts file to properly import the tailwind-highlightjs package. Currently, my configuration looks like this:

import twHLJS from "tailwind-highlightjs";

...

plugins: [twHLJS]

Fortunately, everything seems to be functioning correctly so far.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error in Angular 2 after transition to @types: encountering "require" name not found issue

After transitioning my project from old typings to types-publisher, I have successfully resolved most of my dependencies. However, I am consistently encountering an error that reads Cannot find name 'require'. Below is a snippet from my tsconfig. ...

Error message while attempting to update devextreme-datagrid: "Received HTTP failure response for an unknown URL: 0 Unknown Error"

Need help with updating the devextreme-datagrid. Can anyone assist? lineController.js router.put("/:id", (req, res) => { if (!ObjectId.isValid(req.params.id)) return res.status(400).send(`No record with given id : ${req.params.id}`); ...

Transforming a plain text field into an input field upon clicking a button or icon using Angular/Typescript

I am a beginner with Angular 6 and I'm trying to implement functionality where clicking a button or icon will change a text field into an input field. See the snippet of code and expected output below. Thank you in advance. <div> <mat-for ...

Different method of resolving Typescript modules for 'rxjs' within a single file

I've been stuck in a loop for hours, so here's another tricky question: Currently inside a lerna mono repo with two sub projects, namely ProjectA and ProjectB. Both ProjectA and ProjectB have a dependency on rxjs. In addition, ProjectB depends ...

I need to compile a comprehensive inventory of all the publicly accessible attributes belonging to a Class/Interface

When working with TypeScript, one of the advantages is defining classes and their public properties. Is there a method to list all the public properties associated with a particular class? class Car { model: string; } let car:Car = new Car(); Object. ...

The "healthCarePlans" property is undefined in this context. (Angular 5)

I've searched for solutions to this question without success. Although the error in the title isn't impacting the app's functionality, I'd like to resolve it. <div *ngIf="currentUserData.healthCarePlans.length > 0"> <p ...

Tips for efficiently sorting a string array in JavaScript

Looking to sort an array in a specific numerical order? Check out this example: const files = ['30.png', '10.png', '1.jpeg', '2.jpeg', '12.gif', '4.png'] If you're running into issues when ...

Check the TypeScript file for correct type declarations

I have customized the code inspired by this particular guide in order to showcase uploaded images within an angular application. public uploadFile = (files) => { if (files.length === 0) { return; } var mimeType = files[0].type; i ...

What is the best way to display a menu at the location of a mouse click?

Trying to display a custom menu at the location of a mouse click within a div, but it doesn't seem to be working as expected. The visibility logic works fine, but when clicking on the div, the menu only opens under the Typography element. Should the M ...

Adding items to a Mat Menu dynamically during execution

I am utilizing the mat menu to showcase the available options in my project as a breadcrumb. However, when I attempt to add a new item, it successfully adds to the database and reflects in the array object, but unfortunately, the Angular mat-menu does not ...

Define the data type for the toObject function's return value

Is it possible to define the return type of the toObject method in Mongoose? When working with generics, you can set properties of a Document object returned from a Mongoose query. However, accessing getters and setters on these objects triggers various v ...

Guide on Implementing a New Method into a React Functional Component

I have a component that looks like this: const Abc: React.FC<AbcTypes> = ({...}) => {...} Abc.getLayout = () => {...} I am not sure how to properly define or extend the method getLayout on the Abc component in TypeScript? ...

I have successfully set up micro-cors on my system, and as I tried to compile, I received the following outcome

While working on the Next.js Stripe project, I ran into an unexpected problem that I need help with. ./src/pages/api/webhooks.ts:3:18 Type error: Could not find a declaration file for module 'micro-cors'. 'E:/Project/longlifecoin/node_module ...

Showing Firebase messages in a NativeScript ListView in an asynchronous manner

I am currently struggling to display asynchronous messages in a ListView using data fetched from Firebase through the popular NativeScript Plugin. While I have successfully initialized, logged in, and received the messages, I'm facing challenges in ge ...

Verify whether the type of the emitted variable aligns with the specified custom type

Currently, I am in the process of testing Vue 3 components using jest. My main objective is to receive an emit when a button is clicked and then verify if the emitted object corresponds to a custom type that I have defined in a separate file. Below is an e ...

Working with <html> response data in place of Json in Angular 6

My Angular 6 application needed to call a web service that returns HTML data, which I then had to display within a div. Below is an example of the HTML response data from the service: <html> <head> <title>Chart : 180: Abraham, Male, 1 ...

Receiving the error 'is not assignable to type' in a React component - what steps can I take to gain a better understanding of it?

Exploring the functionalities of the react-spring library, I created a component on codesandbox and then transferred it to my local computer. However, upon importing it, an error message appeared that I am having trouble deciphering. As I am relatively new ...

What is the method for placing a title in the initial column with the help of v-simple-table from Vuetify.js?

I am interested in using the v-simple-table UI component from Vuetify.js to create a table similar to the one shown below. https://i.sstatic.net/QNdpJ.png After creating the code in codesandbox and previewing the output, I noticed that the title is not a ...

When using Ionic 3 on an Android device, the keyboard is causing the tabs and app content to shift upwards

I'm currently working on an Ionic 3 app and encountering a problem. Whenever I click on the search function, the keyboard opens and pushes all the content of the app to the top. https://i.sstatic.net/GaPW8.png https://i.sstatic.net/7d6Fm.png Here i ...

What is the best way to destructure a blend of React props and my own custom props in my code?

I have a requirement to develop a custom React component that serves as a wrapper for the Route component in order to create secure routes. The challenge I am facing is how to access the element property, which is typically specified in the <Route> e ...