Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 371
austinbruch Avatar asked Jan 23 '19 20:01

austinbruch


1 Answers

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;
  }
}
like image 91
Raphaël Avatar answered Nov 10 '22 22:11

Raphaël