Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: lazyload highlight.js & prismjs #297

Merged
merged 1 commit into from
Feb 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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