Middle+
How exactly can a bundle be divided into chunks? What is the difference between code splitting and build-time division?
sobes.tech AI
Answer from AI
Code splitting — is a technique that allows breaking a large JavaScript bundle into smaller parts that are loaded as needed. This improves the loading time and responsiveness of the application.
Methods of splitting:
- Dynamic import — using
import()to load modules on demand. - Static splitting — for example, using build tool configurations (Webpack, Rollup) to specify split points.
Difference between code splitting and build-time splitting:
- Code splitting — is a concept that can be implemented both during build time and dynamically at runtime. It focuses on optimizing loading.
- Build-time splitting — a specific moment when the bundler creates separate chunks based on configuration and the use of dynamic imports.
Example of dynamic import in React:
import React, { Suspense, lazy } from 'react';
const LazyComponent = lazy(() => import('./MyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
Here, MyComponent will be loaded only when needed, reducing the initial bundle size.