Fashio 的 Next.js 網站因一行 `import * as Icons` 向每位訪客傳送 5,727 個圖示
One "import * as Icons" line was shipping 5,727 icons to every visitor of our Next.js site
作者修正 Fashio 的 Next.js 網站兩項客戶端載入問題,將首頁 JavaScript 從 1995 KB 降至 676 KB,減少 66%。原因包括 lucide-react 的命名空間匯入令 5,727 個圖示一併打包(網站只用 90 個),以及 Layout 從 barrel 帶入 24 種語言的訊息資料。作者保留同步語系查找,讓伺服器端渲染(SSR)直接輸出相應語言的導覽。
I look after the marketing site for Fashio, a small product that generates on-model photos and virtual try-ons for fashion e-commerce. The site is a Next.js 16 App Router project: mostly Server Components, markdown content with YAML frontmatter, 24 locales, and a handful of "use client" components for menus and interactive bits.
In August I was doing an accessibility pass and noticed the homepage was shipping roughly 2 MB of JavaScript. For a page that is mostly text, images and a mega-menu, that is absurd. This post is about where that weight came from, how I found it, and the two fixes that took the homepage from 1995 KB to 676 KB of JS.
Neither cause showed up in Lighthouse. That is the part I would like you to take away.
The numbers first
| Before | After icon fix | After both fixes | |
|---|---|---|---|
| Homepage JS | 1995 KB | 1399 KB | 676 KB |
| Average page JS | 1443 KB | – | 675 KB |
That is a 66% cut on the homepage, and the average page landed in the same place because both problems lived in components that wrap every route.
Lighthouse was looking somewhere else
The Lighthouse report I started from had a "reduce unused JavaScript" section, but the largest single saving it listed was a 13.7 KiB polyfill. Nothing in it said "you are shipping an entire icon library" or "you are shipping 23 languages nobody asked for".
That makes sense in hindsight. Lighthouse sees chunks, not the import statements that produced them. When one big chunk is made of hundreds of tiny modules that each "might be used", the report has nothing obvious to point at.
So instead of reading the report harder, I went to the build output and grepped the emitted chunks under .next/static/chunks/ for library fingerprints: strings you know belong to one specific package. An icon library is easy to spot because every icon carries its own name and SVG path data. Once a chunk is full of icon names you have never used anywhere on the site, you know what you are looking at.
Cause 1: the namespace import
Three components rendered icons by name: FeaturesGrid, FeatureCard and the site Layout. The names come from data, not code. The FEATURES array in constants.ts has an iconName per product, and our service pages carry icons in their markdown frontmatter. For example, the page for our ghost mannequin generator lists its feature cards like this:
# content/services/ghost-mannequin-generator.md (trimmed)
- title: "Auto Neck Joint"
icon: "Link"
- title: "Mannequin Removal"
icon: "Eraser"
- title: "Symmetry Correction"
icon: "AlignCenter"
The component side looked like this:
// components/FeaturesGrid.tsx (before, trimmed)
import * as Icons from "lucide-react";
{features.map((feature, index) => {
const IconComponent = (Icons as any)[feature.icon] || Icons.Box;
return ( /* ...<IconComponent /> inside the card */ );
})}
It reads nicely and it works. It also defeats tree-shaking completely. Once you write Icons[someString], the bundler cannot know which exports you will reach for at runtime, so it keeps all of them. lucide-react 0.562.0 exports 5,727 symbols:
$ node -e 'console.log(Object.keys(require("lucide-react")).length)'
5727
We use 90. And because Layout is a client component that wraps every page, every visitor on every route downloaded all 5,727.
The fix: an explicit registry
Tree-shaking needs static, named imports, so the fix is boring on purpose. One file imports exactly the icons we use and exposes a lookup:
// utils/icons.ts (trimmed)
import {
AlertCircle,
ArrowRight,
Box,
Camera,
Layers,
Sparkles,
// ...90 in total
type LucideIcon,
} from "lucide-react";
export const ICONS: Record<string, LucideIcon> = {
AlertCircle,
ArrowRight,
Box,
Camera,
Layers,
Sparkles,
// ...
};
/** Never returns undefined; unknown names fall back to Box. */
export function getIcon(name?: string | null): LucideIcon {
return (name && ICONS[name]) || Box;
}
Each call site became a one-line change:
// components/FeatureCard.tsx
-import * as Icons from "lucide-react";
+import { getIcon } from "@/utils/icons";
- const IconComponent = (Icons as any)[feature.iconName] || Icons.Star;
+ const IconComponent = getIcon(feature.iconName);
That alone took the homepage from 1995 KB to 1399 KB, about 596 KB or 30% of the JS.
The trade-off is real and I wrote it into the file header: icon names still arrive as strings from constants.ts and from frontmatter, so adding a new icon name in content means adding it to utils/icons.ts too, or it silently renders a Box. I accepted that. A content editor seeing a box instead of a shirt is a much smaller problem than every visitor downloading thousands of icons they never see.
Cause 2: every locale in the client layout
1399 KB was still far too much, so I went back to the chunks. The next fingerprint was easier to recognise because it was human-readable: translated message strings from all 24 locales, sitting in the bundle for the English homepage.
The site has 24 locales. components/Layout.tsx is "use client" (it handles the mobile menu and the mega-menu) and it needed the translated nav and footer labels. It got them like this:
// components/Layout.tsx (before, trimmed)
"use client";
import { getSiteMessages } from "@/i18n/messages";
const t = makeT(getSiteMessages(locale) as Record<string, string>);
@/i18n/messages is a barrel. It statically imports every namespace of every locale (pricing copy, landing page copy, legal text) so that server pages can ask for whatever they need. On the server that is fine. Pulled into a client component, it put about 1.3 MB of message tables into the browser bundle so Layout could read a few kilobytes of nav labels.
The fix: a module that imports only the chrome
I added a new module next to the barrel instead of changing it. A parallel i18n refactor was editing i18n/messages/index.ts at the same time, and I did not want a merge fight over a file I did not own.
// i18n/siteChrome.ts (trimmed)
import { DEFAULT_LOCALE } from "./locales";
import { site as enSite } from "./messages/en/site";
import { site as deSite } from "./messages/de/site";
import { site as frSite } from "./messages/fr/site";
// ...one `site.ts` import per locale, nothing else
const SITE: Record<string, Messages> = {
de: deSite,
fr: frSite,
// ...
};
/** Falls back to English for any key a locale has not translated. */
export function getSiteChrome(locale: string): Messages {
const loc = SITE[locale];
return loc && locale !== DEFAULT_LOCALE ? { ...enSite, ...loc } : enSite;
}
// components/Layout.tsx
-import { getSiteMessages } from "@/i18n/messages";
+import { getSiteChrome } from "@/i18n/siteChrome";
- const t = makeT(getSiteMessages(locale) as Record<string, string>);
+ const t = makeT(getSiteChrome(locale) as Record<string, string>);
The site.ts files across all 24 locales come to about 96 KB of source, against 1.3 MB for the full barrel. The bundle dropped by roughly 723 KB, and the homepage landed at 676 KB.
Why I did not lazy-load the locales
The obvious next step is a dynamic import(`./messages/${locale}/site`) so each visitor gets one language. I decided against it, and that was on purpose.
Layout reads the locale from usePathname(), which also runs during SSR. With a synchronous lookup the server renders French nav on /fr/*, in the HTML, before any JavaScript runs. With a dynamic import the first render would fall back to English, and the French labels would swap in after hydration. Users would see a flash, and crawlers would get English navigation on French URLs. For a site with 24 locales that rely on organic search, that is a bad trade for saving a few dozen kilobytes more.
I checked the built HTML afterwards. /fr renders "Tarifs · Shooting IA", /de renders "Preise · KI-Fotoshooting", and /ja renders in Japanese, all server-side.
What I got wrong
I trusted the audit to find the problem. I started from the Lighthouse report, whose biggest item was worth 13.7 KiB. The two problems worth more than 1.3 MB between them were in no report. Grepping the build output took a few minutes, and I should have started there.
I wrote the bug in the first place, in three files. (Icons as any)[name] came from wanting icons to be configurable from markdown. The as any should have been the warning: once a lookup needs a cast to compile, the bundler probably cannot see through it either.
My refactor quietly changed a fallback. FeatureCard used to fall back to Icons.Star; the other two components fell back to Box. getIcon() uses Box everywhere, and its doc comment says "as before", which is only true for two of the three call sites. Nobody has noticed, because every iconName in constants.ts is in the registry today, so nothing falls back on a feature card. It is still a behaviour change I did not mean to make, and it is exactly what "one-line change at each call site" diffs hide.
The registry fails silently by design. At least one icon name in our markdown, HighDefinition, does not exist in lucide at all. It fell back to a box before and it still does. A build-time check that compares every icon: and iconName value against the keys of ICONS would catch both a typo and a forgotten registry entry. I have not written it yet.
A separate i18n change broke the build that same day. Two new English message files were annotated export const about: Messages = {}, but Messages is derived from the English tables, so TypeScript reported 'about' is referenced directly or indirectly in its own type annotation. The fix was to remove the annotation. Every other English file already left it off, and only the other locales annotate against the derived type. It had nothing to do with bundle size, but it cost me time while I was trying to measure a build that would not finish.
Checklist if your Next.js bundle looks too big
- Look at the emitted chunks, not just the Lighthouse summary. Search them for strings from libraries you suspect.
- Search the codebase for
import * asfrom any large package, especially icon sets, date libraries and lodash-style utility packages. - Check every
"use client"component that wraps many routes (layouts, headers, providers). Whatever it imports ships everywhere. - Be careful with barrels (
index.tsthat re-exports a lot) imported from client code. A server-side convenience becomes a client-side payload. - Before lazy-loading anything that affects rendered text, check what SSR outputs without it.
If you are curious what the site actually does, it turns flat-lay product photos into AI fashion models for e-commerce catalogs, and the mega-menu that used to carry all those icons now links to pages like virtual try-on at a third of the weight.
This post was written with AI assistance and reviewed by the author.
來源:DEV Community · dev.to