Better filenames for React Suspense/Lazy chunks

React Suspense allows you to easily add code-splitting into your application by lazy loading certain components, replacing them with something else until they've download.

Before code-splitting, your webpack build might generate a single file for all of your application code.

Imagine a React application with multiple pages and components. One of these pages is MyPage.

import React from "react";
import HeavyComponent from "./HeavyComponent";

const MyPage = () => (
<div>
<h1>I am the page</h1>
<HeavyComponent />
</div>
);

export default MyPage;

Let's lazy load the HeavyComponent so it's code isn't downloaded by the browser until a visitor hits MyPage for the first time.

import React, { Suspense, lazy } from 'react';

const HeavyComponent = lazy(() => import('./HeavyComponent');

const MyPage = () => (
<div>
<h1>I am the page</h1>
<Suspense fallback={<p>Loading...</p>}>
<HeavyComponent />
</Suspense>
</div>
);

export default MyPage;

HeavyComponent now gets split into a seperate chunk with a numbered filename in your build directory e.g. 1.js

Better filenames with webpackChunkName

1.js isn't a very helpful filename. Fortunately with webpackChunkName in an inline comment, we can instruct webpack to name the file something much friendlier.

const HeavyComponent = lazy(() => import(/* webpackChunkName: "HeavyComponent" */ './HeavyComponent');

Now the chunk will be named HeavyComponent.js

Ooooh, ultrawide! 😍