Skip to content

Commit

Permalink
perf: lazyload highlight.js & prismjs (#297)
Browse files Browse the repository at this point in the history
  • Loading branch information
SukkaW authored Feb 27, 2023
1 parent 22cb935 commit d31764c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 3 deletions.
13 changes: 11 additions & 2 deletions lib/highlight.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import hljs, { HighlightResult } from 'highlight.js';
import type { HLJSApi, HighlightResult } from 'highlight.js';
import stripIndent from 'strip-indent';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const alias = require('../highlight_alias.json');

let hljs: HLJSApi | undefined;

interface Options {
autoDetect?: boolean;
caption?: string;
Expand Down Expand Up @@ -31,7 +33,10 @@ function highlightUtil(str: string, options: Options = {}) {
} = options;
let { wrap = true } = options;

hljs.configure({ classPrefix: useHljs ? 'hljs-' : ''});
if (!hljs) {
hljs = require('highlight.js');
}
hljs.configure({ classPrefix: useHljs ? 'hljs-' : '' });

const data = highlight(str, options);
const lang = options.lang || data.language || '';
Expand Down Expand Up @@ -104,6 +109,10 @@ function highlight(str: string, options: Options) {
let { lang } = options;
const { autoDetect = false } = options;

if (!hljs) {
hljs = require('highlight.js');
}

if (lang) {
lang = lang.toLowerCase();
} else if (autoDetect) {
Expand Down
5 changes: 4 additions & 1 deletion lib/prism.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import Prism from 'prismjs';
import stripIndent from 'strip-indent';
import prismLoadLanguages from 'prismjs/components/';

let Prism: typeof import('prismjs') | undefined;

// https://github.com/PrismJS/prism/issues/2145
import prismComponents from 'prismjs/components';

Expand All @@ -26,6 +27,8 @@ import escapeHTML from './escape_html';
* @param {String} language
*/
function prismHighlight(code: string, language: string) {
if (!Prism) Prism = require('prismjs');

// Prism has not load the language pattern
if (!Prism.languages[language] && prismSupportedLanguages.includes(language)) prismLoadLanguages(language);

Expand Down

0 comments on commit d31764c

Please sign in to comment.