Load only highlight.js library using TypeScript, not default with all languages loaded
Asked Answered
M

2

7

As the official highlight.js usage document suggests:

The default import imports all languages! Therefore it is likely to be more efficient to import only the library and the languages you need:

import hljs from 'highlight.js/lib/highlight';
import javascript from 'highlight.js/lib/languages/javascript';
hljs.registerLanguage('javascript', javascript);

I am trying to load just the highlight.js library, along with individual language modules so as to reduce my footprint for my TS app.

Using the @types/highlight.js declarations file, the only way (that I can find) to import highlight.js is like this:

import * as hljs from 'highlight.js';

Unfortunately, that loads the default export, which has all of the shipped languages loaded.

Looking into the highlight.js module, I want to do something like this:

import * as hljs from 'highlight.js/lib/highlight.js';
import * xml from 'highlight.js/lib/languages/xml';
...
hljs.registerLanguage('xml', xml);

so I only get the library itself, along with the only language I need (xml).

So far, I've been able to add these lines in a .d.ts file to get TypeScript to not complain about these imports:

declare module 'highlight.js/lib/highlight';
declare module 'highlight.js/lib/language/xml';

But of course, that means I lose my content assist when importing hljs. I could duplicate the content of @types/highlight.js into my own .d.ts file, but I'd really like to avoid that.

Is there any way to I can proxy the declarations from @types/highlight.js onto the module highlight.js/lib/highlight'? Or maybe some other approach I'm missing.

Thanks in advance.

Moderation answered 23/1, 2019 at 20:8 Comment(0)
T
2

I solved this problem by creating a Javascript file that requires only the languages I need:

myhighlight.js

var hljs = require('../../../node_modules/highlight.js/lib/highlight');
hljs.registerLanguage('typescript', require('../../../node_modules/highlight.js/lib/languages/typescript'));
hljs.registerLanguage('json', require('../../../node_modules/highlight.js/lib/languages/json'));
module.exports = hljs;

And by importing this file in my Typescript code:

import hljs from './myhighlight';

export class SomeClass {
  highlight(code: string) {
    return hljs.highlightAuto(code).value;
  }
}
Tough answered 30/1, 2020 at 14:22 Comment(0)
F
0

Just include the types by adding this line in the top of one of your *.d.ts files (e.g., global.d.ts)

/// <reference types="highlight.js/types/index.d.ts" />
Flatten answered 4/9, 2022 at 22:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.