Skip to content

Instantly share code, notes, and snippets.

@zaverden
Created February 24, 2022 05:08
Show Gist options
  • Save zaverden/9f5317e9124803fd9c89973c9394d2f6 to your computer and use it in GitHub Desktop.
Save zaverden/9f5317e9124803fd9c89973c9394d2f6 to your computer and use it in GitHub Desktop.

Tree shaking in NextJS

├── components/
│   ├── index.js
│   ├── c-big.js
│   └── c-small.js
├── pages/
│   └── index.js
├── reexport.js
└── reexport-ns.js
rm -rf .next/ && npm run build && ncdu .next/static/

Compare size of .next/static/ with different pages/index.js

0. Baseline (direct import and usage)

import { CSmall } from "../components/c-small.js";
import { CBig } from "../components/c-big.js";
export default function Home() {
  return (
    <>
      <CSmall />
      <CBig />
    </>
  );
}

Output size: 1.5 MiB

1. Unused direct import

import { CSmall } from "../components/c-small.js";
import { CBig } from "../components/c-big.js";
export default function Home() {
  return <CSmall />;
}

Output size: 372.0 KiB - ✅ SHAKEN

2. Unused named import from barrel

import { CSmall, CBig } from "../components";
export default function Home() {
  return <CSmall />;
}

Output size: 372.0 KiB - ✅ SHAKEN

3. Namespace import from barrel

import * as C from "../components";
export default function Home() {
  return <C.CSmall />;
}

Output size: 372.0 KiB - ✅ SHAKEN

4. Namespace import from barrel via reexport

import * as C from "../reexport.js";
export default function Home() {
  return <C.CSmall />;
}

Output size: 372.0 KiB - ✅ SHAKEN

5. Namespace import from barrel via namespaced reexport

import { C } from "../reexport-ns.js";
export default function Home() {
  return <C.CSmall />;
}

Output size: 372.0 KiB - ✅ SHAKEN

export * from "./c-big.js";
export * from "./c-small.js";
export * as C from "./components";
export * from "./components";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment