DEV Community

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

Posted on

Code Splitting With Dynamic Imports


  • 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 (
      <Suspense fallback={<div>Loading...</div>}>
        <SubComponent />
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.

Top comments (0)