Blog post image

How to do code splitting using React.Lazy, Typescript and Webpack

React is one of the main go-to things you use when you need to build a web application no matter if it’s a one-pager or a whole dashboard, but let’s face it, React is a bit bloated and when compiling bigger projects to production we end up with quite big packages. When a people visits our website they have to load the whole React application to see the first page and if the bundle is sized 2-3mb it is considered large.

Luckily we can optimise this by using React.Lazy to first lazy load our pages or components when they are needed / requested by the visitor. This article will give you a guide on how you can start code splitting your React web application using React.Lazy and webpack.

What is code splitting?

Code splitting is a term used when we split up our bundle into multiple files that can be loaded asynchronously. Normally we will send the whole bundle to our visitor and let them load it all at the beginning, but by using code splitting we can split the bundle into bits that will be served when requested.

We have to assume that not all visitors are viewing every single page of our website or using every single feature on our dashboard and therefore there is no reason to load elements and pages that aren’t needed. To give you an example: When bundling all of your pages into one file they might be 2-7mb, but when using React.Lazy to code split your code the visitor might only have to load 80-120kb on the first visit. As you can see it is a huge reduction and therefore also much more sustainable.

Why should i use React.Lazy to code split my project?

There are many reasons why it is a good idea to use React.Lazy to split your code into chunks, but the two biggest is the following:

1: The visitor won’t have to download the whole web application if they are only visiting the first page. This means less data needed to be downloaded in order to present your website. Lowering the amount of data downloaded is better for the pollution that the internet causes since less power is required by the devices used by the visitor, the visitors router, the router points in between the web server and the visitor and also the server itself.

2: When splitting your code using React.Lazy then your web application becomes more accessible to people in areas with slow internet. Imagine people with a 3G connection having to download up to 7mb before seeing your page. They would most likely find another website instead.

Code splitting and Typescript

Before we begin it is worth pointing out that if you use Typescript you might run into some problems unless you have set up your tsconfig correct. Luckily Webpack won’t be using split chunks unless both Typescript and your React web application supports it, therefore if you only see one bundle file you have an error somewhere.

To use code splitting / split chunks together with Typescript we recommend using the following setup below. As you can see, we’ve changed the module to esnext instead of commonjs since commonjs does not support split chunks and async import. If you set the module to commonjs or another type that doesn’t support split chunks, then webpack won’t be splitting your code.

"compilerOptions": {
  "esModuleInterop": true,
  "lib": ["es5", "es2015", "es2016"],
  "module": "esnext",
  "moduleResolution": “node",
}

It is also worth to mention that in some cases you want to use comments to name your chunks, and if you tsconfig is removing comments, then you cannot name your chunks specifically. If this is not important, we can simply name the chunk files in webpack instead.

How to set up React.Lazy and get started

When using React.Lazy to code split your bundle it is fairly easy to get started and actually split your code into chunks. Below here you can see step for step how to set up React.Lazy.

As the first step you need to import the components you want to split into your React project as lazy loading elements. This can be done in two ways. One will simply import the component and let webpack name it and the other will strictly name the chunk file (This requires comments not to be removed by Typescript).

const HomePage = React.lazy(() => import('./Homepage'));


The example above is showing how you can lazy import a homepage component without naming it.

const HomePage = React.lazy(() => import(/*webpackChunkName: “home-page” */ ’./Homepage'));


The example above is showing how you can lazy import a homepage component and name the chunk at thee same time using a comment.

If you have chosen to name your own split chunks then they will be compiled into a filename looking somewhat like this:



home-page.45ngdk452.chunk.js.

Once you have chosen which components you want to use React.Lazy on, you have to add the suspense function. When loading your web application these lazy loaded components will first be requested once they are needed and therefore we need something to happen in between the request and the rendered component. This is where React.Suspense comes in the picture. If you haven’t worked with the suspense function before, then you can read the documentation here: https://reactjs.org/docs/react-api.html#reactsuspense.

After adding the suspense function to those components using React.Lazy we need to instruct Webpack to do code splitting. This is the easiest step since it is done only using a single setting in your output section. You can configure your chunk names in many ways but in this tutorial we will go with the easiest setting.

module.exports = {
         output: {           
             chunkFilename: ‘[id].js',
       
         };
};

The above example is taken from Webpacks own example code and what it does it simply to name the code splitter chunk files with a random id.

Integrating

To use your new code splitted chunk files you do exactly the same as before. If you chose to call your project app.js, then after using React.Lazy you will notice that you still have a file called app.js (the compiled bundle). This file will be your main file that you include in your HTML page and then your React web application will take care of importing the chunks when they are needed. Therefore you don’t need to import the chunks in your HTML, you simply import the same file as before and then magically React will take care of the rest.

Author