BS Blog

Removing Bloat from VueJs (HighlightJS Example)

Published Feb 01, 2021 | 0 Comments

Sometimes when you're developing using 3rd party libraries, you inherit a lot more than you bargained for. Sometimes this is in dependencies, othertimes you don't realize what's included and other times you've just picked the wrong library for your use-case (dummy).

I came across this trying to implement HightlightJS for this very site.

When building for production, I was getting warnings about my chunk sizes, specifically in vendor. Using Source Map Explorer I was able to clearly see there was an issue with HightlightJS size:

Whaaaaat

65% of my app was HightlightJS libs!! looking further down I could see this was a result of every language known to man being imported, meanwhile my poor little blog only really deals with javascript, php, and occassionaly some others.

So how do I fix this?

Some libraries it's easy enough to just import the components that you need, however HightlighJS is kind of all or nothing. Webpack to the rescue! Webpack has a "ContextReplacementPlugin" that allows replacing/exluding parts of a library useing Regex.

So inside my vue.config.js:

javascript
module.exports = { configureWebpack: { plugins: [ new webpack.ContextReplacementPlugin( /highlight\.js\/lib\/languages$/, new RegExp(`^./(${['javascript', 'php', 'bash', 'yaml'].join('|')})$`), ), ] }, }

This allows me to "replace" anything that is not the languages I want with... nothing, I replaced them with nothing. Gone, kill it, don't want it!

Now lets look at the results:

Vue trimmed

760KB killed!! Woooooo.