DEV Community

Discussion on: We reduced our vendor.js from 210kb to 16kb in about five minutes of work and ten lines of code

Collapse
 
pavelloz profile image
Paweł Kowalski • Edited

You can make a second step, and load it when its needed (or not load when its not needed - i assume not every page needs it).

Simplified example for prism.js:

if ($q('code[class*="language-"]')) {
  import(/* webpackChunkName: "syntaxHighlighting" */ './js/syntaxHighlighting');
}

Notes:

  • chunkName makes it prettier than 0.fade4.js :)
  • $q - is an alias for document.querySelector
  • file is not exporting anything, just initializing, so there is no need to run .then()... ;)
  • if you have something that you want to prefetch/preload because its also an option: webpack.js.org/guides/code-splitti...
  • link above has also some links to help you understand webpack bundle and make better informed decisions: webpack.js.org/guides/code-splitti...
  • you can construct path to file to be imported dynamically, so you can have a function (simplified, naive, just for demo purposes):
const dynamicImport = p => import(`modules/${p}`).then(m => m.default())

And then call it from your js, when something happens.

If dev.to wasnt so heavy into react i could do some good with my webpack knowledge, but i dont want to get dirty with all the abstractions in there ;)