Tamaño del bundle y optimización del código
Reduzca el tamaño del bundle del Worker y el uso de CPU para que su código edge cargue más rápido y se ejecute dentro de los límites.
Tamaño del bundle y optimización del código es una lección gratuita de Edge Computing with Cloudflare Workers & Deno en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Edge Computing with Cloudflare Workers & Deno, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Edge Computing with Cloudflare Workers & Deno incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Why Bundle Size Matters
Workers have a script size limit (1 MB compressed on the free plan, more on paid).
Smaller bundles mean:
- Faster parse and startup
- Lower memory footprint
- Reduced cold-start impact
Optimizing your code is a direct performance win at the edge.
Measure Before Optimizing
Wrangler reports your bundle size on every build. Always measure first.
wrangler deploy --dry-run
# Total Upload: 142.18 KiB / gzip: 38.94 KiBTree Shaking
Use ES module import/export so the bundler can tree-shake unused code.
Import only what you need, never the whole library when a single function will do.
// Good: only pulls debounce
import debounce from 'lodash-es/debounce';
// Bad: pulls all of lodash
import _ from 'lodash';Prefer Lightweight Dependencies
Heavy npm packages bloat bundles fast. Prefer small, edge-friendly libraries.
- Use the platform
URL,crypto.subtle, andfetchinstead of polyfills - Swap moment.js for a tiny date helper
- Audit with a bundle analyzer
Use Web Standard APIs
Workers and Deno expose many Web Platform APIs natively, so you avoid bundling polyfills.
// Native crypto, no dependency needed
const hash = await crypto.subtle.digest(
'SHA-256',
new TextEncoder().encode('hello')
);Minification
Wrangler minifies production builds by default, but confirm it is enabled.
[build]
minify = trueReduce CPU Time
Workers bill and limit by CPU time, not wall-clock. Optimize hot paths:
- Avoid synchronous loops over huge arrays
- Cache computed results in KV or memory
- Stream large responses instead of buffering
Stream Instead of Buffer
Streaming sends data as it is produced, keeping memory low and CPU steady.
const { readable, writable } = new TransformStream();
response.body.pipeTo(writable);
return new Response(readable, response);Lazy-Load Rarely Used Code
Dynamic import() can defer loading code paths that are not always needed, keeping the initial module lean.
if (needsHeavyFeature) {
const { process } = await import('./heavy.js');
process();
}Analyze Your Bundle
Use an analyzer to see which dependencies dominate. esbuild (which Wrangler uses) can emit a metafile.
esbuild src/index.ts --bundle --metafile=meta.json
# upload meta.json to esbuild.github.io/analyzeBest Practices Summary
To keep edge code fast and small:
- Measure bundle size on every deploy
- Tree-shake and import narrowly
- Prefer native Web APIs over polyfills
- Minify, stream, and lazy-load
- Cut CPU time in hot paths
Quick Check
Which technique most directly lets the bundler remove unused library code?
Recap
You optimized both size and speed:
- Measure first, then tree-shake and minify
- Use native Web APIs and lightweight deps
- Stream and lazy-load to cut memory and CPU
- Analyze the bundle to find offenders
Lean Workers start faster and cost less, every kilobyte counts at the edge.
Preguntas frecuentes
¿La lección «Tamaño del bundle y optimización del código» es gratis?
Sí — el texto completo de «Tamaño del bundle y optimización del código» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Edge Computing with Cloudflare Workers & Deno, actualiza a CoddyKit PRO. El curso de Edge Computing with Cloudflare Workers & Deno incluye 4 lecciones en total.
¿Qué aprenderé en «Tamaño del bundle y optimización del código»?
Reduzca el tamaño del bundle del Worker y el uso de CPU para que su código edge cargue más rápido y se ejecute dentro de los límites. Practicas Edge Computing with Cloudflare Workers & Deno con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Edge Computing with Cloudflare Workers & Deno?
No se requiere experiencia previa. Edge Computing with Cloudflare Workers & Deno en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Tamaño del bundle y optimización del código»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Edge Computing with Cloudflare Workers & Deno?
Sí. Cada lección de Edge Computing with Cloudflare Workers & Deno incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Estrategias de almacenamiento en caché
- Cold starts y warmups
- Monitorización y registro
- Tamaño del bundle y optimización del código