2

How do we use highlight.js inside a lit element web component if we are importing highlight.js in a index.html file.

So for example in the head element of index.html we may have this:

    <link
      rel="stylesheet"
      href="https://unpkg.com/@highlightjs/[email protected]/styles/default.min.css"
    />
    <script type="module">
      import hljs from 'https://unpkg.com/@highlightjs/[email protected]/es/highlight.min.js';
      //  and it's easy to individually load & register additional languages
      import go from 'https://unpkg.com/@highlightjs/[email protected]/es/languages/go.min.js';
      hljs.registerLanguage('go', go);
    </script>

Which makes hljs available, but if we try to use it inside the connectedCallback function of the web component like this:

this._code = hljs.highlightAuto(this.innerHTML);

The linting creates the error:

Cannot find name 'hljs'.(2304)
any

So how should we go about referencing hljs within the web component?

1
  • Note that the highlightElement function takes an element, not a string (so just pass it this). As for how to get your linter to not complain: tell it that hljs is a global/external (the linting config docs cover how to do that) Commented Apr 17, 2024 at 1:56

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.