惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Last Week in AI
Last Week in AI
阮一峰的网络日志
阮一峰的网络日志
P
Proofpoint News Feed
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
MongoDB | Blog
MongoDB | Blog
云风的 BLOG
云风的 BLOG
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
J
Java Code Geeks
WordPress大学
WordPress大学
T
The Blog of Author Tim Ferriss
V
Visual Studio Blog
小众软件
小众软件
Microsoft Azure Blog
Microsoft Azure Blog
博客园_首页
IT之家
IT之家
Vercel News
Vercel News
C
Check Point Blog
Google DeepMind News
Google DeepMind News
月光博客
月光博客
D
DataBreaches.Net
酷 壳 – CoolShell
酷 壳 – CoolShell
美团技术团队
Y
Y Combinator Blog
Hugging Face - Blog
Hugging Face - Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Optimizing Vite Build Output: A Practical Guide to Tree-S...
Avwerosuoghe · 2026-05-23 · via DEV Community

I used to think bundle optimisation was someone else's problem. I'd write code using convenient namespace imports like import * as utils from './utils', run npm run build, and ship whatever came out. My bundles kept growing: 200KB, 300KB, 450KB, but I assured myself it was fine. After all, browsers were getting better, internet connections were faster, and devices were becoming more powerful.

Then I tested my 450KB utility library on a 3G connection. Four seconds to download. Lighthouse gave me an embarrassing performance score. That's when I learned I was shipping 60% unused code.

This article covers what I discovered about tree-shaking in Vite, the mistakes I was making, and how I fixed them.

What Tree-Shaking Actually Does

Tree-shaking is dead code elimination for ES modules. When you use import and export, you create a static dependency graph. Vite (via Rolldown) traces through this graph and removes exports that aren't being consumed. Basically, tree-shaking only works when the bundler can prove code is unused. If you give it ambiguous signals, it keeps everything safe.

The Anti-Patterns I Was Using

Take a utility component called dashboard.utils.ts as a real example. It exports eight standalone functions: hasActiveFilters, mapApplicationToTableData, resetPagination, updateFilterState, updatePagination, mapJobStats, normalizeFilter, and buildPagination. I only needed one, but here's how I used to import it

Vite can statically analyse and determine that only resetPagination is accessed here, and drop the rest, but that's the bundler doing you a favour, not you writing intentional code. You've imported the entire module and handed the cleanup responsibility to your build tool. It works until it doesn't.

And it stops working the moment you do something like this:

Once the namespace object is passed to console.log or spread into another structure, the bundler can no longer prove at build time which properties will be accessed at runtime. It has no choice but to keep all eight exports: hasActiveFilters, mapJobStats, buildPagination, and everything else, just in case.

This is a trap because the first version looks harmless. It gets past your linter, the build succeeds, and you move on. Then three weeks later, someone adds a debug log, passes the namespace to a utility, and suddenly your bundle is carrying dead weight you didn't notice.

The "Just in Case" Import Pattern

Eight dashboard utility functions imported. One actually used. Seven along for the ride on every page load.

The Fixes I Implemented

Named Imports Only

This provides a clear signal to the bundler: only resetPagination is needed. mapJobStats, buildPagination, normalizeFilter, and the rest can be safely removed from the final output.

Switching from namespace imports and over-importing to precise named imports was the single biggest improvement.

Pure Function Annotations

I noticed /* @\_\_PURE\_\_ */ comments in my build output. These tell the minifier a function call has no side effects, meaning if the return value is never used, the entire call can be safely removed.

In the snipper above, both resetPagination and buildPagination just take input, compute a value, and return it. No HTTP calls, no mutations, no DOM access. They have zero side effects. That's exactly what Vite looks for when deciding whether to annotate a call as pure:

Strategic Dynamic Imports

Imagine your project grows and you have a helpers/ directory with multiple utility files, date.helper.ts, dashboard.utils.ts, and others. The temptation is to import them all eagerly:

Every page component, all its dependencies, and all its templates are now bundled together and loaded on the first request, regardless of which page the user is actually visiting.

Instead, lazy-load each page so that it becomes its own separate chunk:

A user who only visits the dashboard never downloads the profile management or jobs page. The router calls loadPage('dashboard') on navigation, and everything else stays unloaded until it's needed.

My Current Practices

1. Named imports only
No import * as unless necessary.

2. Don't pass namespace objects to functions
Log specific properties, not the whole namespace.

3. Dynamic imports for optional features
If it's not needed for the initial render, lazy-load it.

4. Review dependencies
Replace non-tree-shakable libraries when possible.

Key Takeaway

Vite's tree-shaking is powerful, but it only works with your cooperation. Write code that gives the bundler clear signals about what's actually used.

Check your bundle. You might be shipping more dead code than you think.