by Eduard · 3y ago · 0 comments
import hljs from 'highlight.js';
pulls in over a Megabyte of hundreds of programming language syntax definitions.Do you really need Mathematica, "ISBL", and "GML" — or would a curated list of popular programming languages such as Python, Java, JavaScript, and HTML ("xml.js" ) be enough? This results in a massive reduction down to ~70 kilobytes.
Even better: load this reduced size of highlight.js only on demand, leveraging Webpack's "import(..) to webpack chunk" mechanism:
const getHighlightJs = async function() {
let result;
if (window.hljs) {
result = window.hljs;
}
else {
result = (await import('highlight.js/lib/core')).default;
const javascript = (await import('highlight.js/lib/languages/javascript')).default;
result.registerLanguage('javascript', javascript);
const xml = (await import('highlight.js/lib/languages/xml')).default;
result.registerLanguage('xml', xml);
// xml provides html/html5 highlighting
window.hljs = result;
}
return result;
};
const lazyHighlightAll = async function() {
let result = null;
// see https://highlightjs.org/usage/
// highlight.js's hljs.highlightAll() matches on 'pre > code'
const hasHighlightableCode = document.querySelector('pre > code') ? true : false;
if (hasHighlightableCode) {
const hljs = await getHighlightJs();
hljs.highlightAll();
result = hljs;
}
return result;
};
document.addEventListener('DOMContentLoaded', function() {
lazyHighlightAll();
});The one you complain about is specifically about importing everything, because that's what the user wants in that case, importing it like that signals that that's what the user wants.
Otherwise you can do the following:
import hljs from 'highlight.js/lib/core';
import javascript from 'highlight.js/lib/languages/javascript';
hljs.registerLanguage('javascript', javascript);
Maybe the defaults should be different, but a 30 second read of the most basic information available in the repository would reveal how you can use it the way you want too, without any complication that the rest of your comment seems to want to introduce.They'd move begin searching for a new solution.
Some would recognize they should substitute their language.
Then a tiny fraction of users will actually read your documentation :)
76K node_modules/highlight.js/lib/core.js
20K node_modules/highlight.js/lib/languages/javascript.js
But I agree with you, that you probably want to only load it when really needed, especially if your total budget is 500kb which this would take a big part of it already.Edit: I see now their budget was actually more than 1MB actually, as they for some reason only "really care" about gzip'd sizes... Then I wouldn't say it's so bad to just say fuck it and do it the easy way. Saves any latency introduced by lazy-loading it too.
The two different variants written are six of one half a dozen of the other. There's nothing stopping you from writing the imports + register in one file and dynamically importing it in a dom loaded event in another.