Pragmatic Code-splitting with Preact and Webpack

Code-splitting keeps your bundle fit and sexy

Photo by Matteo Maretto on Unsplash

I’m going to assume you knew what code-splitting is all about or overheard about it. Whatever it is, I’m gonna show you how you can do it too!

OK let’s make this quick! Do it!

👶 The Babel plugin that makes it happen

// babel.config.jsmodule.exports = {
plugins: ["@babel/plugin-syntax-dynamic-import"]

Code-splitting is achieved with the JS standard syntax import('<path_to_file>') . When webpack sees this dynamic imports during compilation, it will create a separate ‘chunk’ for each of them.

For example, import('./complicated_hello_world.jsx') will output by webpack as complicated_hello_world.sdhs98ewshd98.js in your build/dist folder.

👲 AsyncComponent.jsx

Create this AsyncComponent.jsx

💂 Routes’ loader component

We are gonna do route-based code-splitting first. We will do the more granular component-based splitting in a second.

OK, say you have a route folder called Payment , create a file inside called Payment.loader.jsx :

👵 Usage

👷 Component-based code-splitting

Now that we have done code-splitting on our routes, let’s apply the same approach on our components with a breeze!

Say we don’t wanna ship our monstrous Terms and Condition texts with our initial app.js bundle. First, we create a component for the TnC content:

Make sure it’s ‘export default’

Then in our main TnC component:

So what’s gonna happen is when TermsOfUse is rendered, the <AsyncComponent /> will dynamically download our <TermsOfUseContent /> while showing a spinner as dictated in the <AsyncComponent /> , and display it once it’s ready.

And that’s it! No learning more third-party libraries needed. Retain full control of your destiny. Write your own JS at your skill level at your own pace with the learn-once idiomatic React paradigm. Plus, you are now riding the code-splitting train too! 🚡

Untitled by Kheoh Yee Wei



Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store