DEV Community

Cover image for Code Splitting With Dynamic Imports
Russ Brooks
Russ Brooks

Posted on

2

Code Splitting With Dynamic Imports

Benefits

  • Better UX
    • Breaks your JavaScript bundle into multiple modules that intelligently load only when a user uses that functionality.
    • Loading and wait times are improved application-wide.
  • Hosting-Costs - Lowers overall "Bytes Transferred" every month.

How To

Dynamic Imports is already enabled by default in WebPack. All you need to do is make a small change to your "import" lines, and wrap the component in React's <Suspense> component. Eg:

import React, { Suspense } from 'react';

const SubComponent = React.lazy(() => mport('./SubComponent'));

function MyComponent() {
  return (
    <div>
      <Suspense fallback={<div>Loading...</div>}>
        <SubComponent />
      </Suspense>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

I had to comment out this line of our tsconfig.json or I got an transpile error. This makes it default back to "CommonJS", which is an older JS standard, but that had no effect on our compiles. Our large React/TS application compiled fine. This is an Output setting; not an Input setting. It only changes the format of JS files that are output to the browser.

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "jsx": "react",
    "lib": ["es6", "dom"],
    // "module": "es6",
    "moduleResolution": "node",
    "sourceMap": true,
    "strictNullChecks": true,
    "target": "es5",
    "types": ["jest", "node", "react", "@testing-library/jest-dom"],
    "esModuleInterop": true
  },
  ...
}
Enter fullscreen mode Exit fullscreen mode

You can see in CDT, this caused two additional "chunk.js" files to be created, and these files only loaded when that user clicked on that functionality - opened a modal in this case.

Screenshot of Chrome Dev Tools

Have you team continue to adopt this import syntax, and gradually your JS code will be split into smartly loading modules.

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay