亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
Why Code Splitting Matters
Code Spliting in React with React.lazy and Suspense
Key Points:
Code Splitting in Vue with Async Components
Differences:
Route-Based Splitting: The Lowest-Hanging Fruit
Advanced: Splitting Libraries and Shared Code
In Webpack:
In Vite:
Gotchas and Best Practices
Home Web Front-end H5 Tutorial Code Splitting in Modern Web Apps: A Guide for React and Vue

Code Splitting in Modern Web Apps: A Guide for React and Vue

Jul 31, 2025 pm 12:35 PM
web application code splitting

代碼分割對現(xiàn)代Web性能至關(guān)重要,能顯著提升加載速度和用戶體驗。1. 在React中使用React.lazy和Suspense實現(xiàn)路由級代碼分割,僅在需要時加載組件,并通過Suspense顯示加載狀態(tài);2. Vue中使用defineAsyncComponent或動態(tài)import()實現(xiàn)異步組件加載,支持錯誤處理和延遲加載;3. 路由級分割是最有效的起點,因與用戶導(dǎo)航一致且工具鏈自動支持;4. 通過Webpack或Vite配置提取共享依賴,避免重復(fù)加載第三方庫;5. 避免過度分割、合理使用預(yù)加載、監(jiān)控包體積并優(yōu)雅處理加載狀態(tài),以實現(xiàn)最佳性能。正確實施代碼分割可讓React或Vue應(yīng)用更快速響應(yīng)。

Code splitting is no longer a nice-to-have — it’s essential for modern web performance. As React and Vue apps grow in complexity, loading everything upfront leads to slow initial loads and poor user experience. Code splitting helps by breaking your JavaScript bundle into smaller chunks, loading only what’s needed when it’s needed.

Here’s how to implement effective code splitting in both React and Vue apps.


Why Code Splitting Matters

Large bundles mean longer download, parse, and execute times — especially on mobile or slow networks. Code splitting improves:

  • Initial load time: Users see content faster.
  • Memory usage: Less unused code in memory.
  • Caching efficiency: Smaller, more focused chunks can be cached independently.

The key idea: split at natural boundaries, like routes, components, or feature modules.


Code Spliting in React with React.lazy and Suspense

React provides built-in support for lazy loading components using React.lazy and Suspense.

import { lazy, Suspense } from 'react';
import { BrowserRouter as Router, Routes, Route } from 'react-router-dom';

const HomePage = lazy(() => import('./pages/HomePage'));
const AboutPage = lazy(() => import('./pages/AboutPage'));

function App() {
  return (
    <Router>
      <Suspense fallback={<div>Loading...</div>}>
        <Routes>
          <Route path="/" element={<HomePage />} />
          <Route path="/about" element={<AboutPage />} />
        </Routes>
      </Suspense>
    </Router>
  );
}

Key Points:

  • React.lazy only works with default exports.
  • Suspense lets you show a fallback while the component loads.
  • Best used at route level — ideal for splitting by page.

? Note: For server-side rendering (SSR), you’ll need additional tooling (like Next.js or custom webpack loaders) since React.lazy is client-side only.

You can also split non-route components:

const CommentSection = lazy(() => import('./components/CommentSection'));

But only do this for heavy, below-the-fold components.


Code Splitting in Vue with Async Components

Vue handles async components natively using defineAsyncComponent (Vue 3) or dynamic import().

import { defineAsyncComponent } from 'vue';
import { createRouter } from 'vue-router';

const HomePage = () => import('../views/HomePage.vue');
const AboutPage = defineAsyncComponent(() =>
  import('../views/AboutPage.vue')
);

const routes = [
  { path: '/', component: HomePage },
  { path: '/about', component: AboutPage }
];

const router = createRouter({ history: createWebHistory(), routes });

Differences:

  • Using import() directly in routes automatically enables code splitting (Vue Router + Vite or webpack).
  • defineAsyncComponent gives more control (e.g., error handling, loading delays):
const AsyncComponent = defineAsyncComponent({
  loader: () => import('./HeavyComponent.vue'),
  delay: 200,
  errorComponent: ErrorComponent,
  timeout: 5000
});

This is useful for non-route components that are expensive to load.


Route-Based Splitting: The Lowest-Hanging Fruit

Both React and Vue benefit most from route-level splitting because:

  • It aligns with user navigation.
  • Tools like React Router and Vue Router integrate seamlessly with bundlers.
  • Each route becomes a separate chunk automatically when using dynamic import().

Webpack, Vite, and other bundlers detect import() and split accordingly — no extra config needed in most cases.

? Pro tip: Name your chunks for better debugging:

const AboutPage = lazy(() => import(/* webpackChunkName: "about-page" */ './pages/AboutPage'));

In Vue with Vite, use:

() => import('../views/About.vue').then(m => m.default)
// Vite handles naming automatically in most cases

Advanced: Splitting Libraries and Shared Code

Even with route splitting, you might end up duplicating libraries (e.g., Lodash, date-fns). Use your bundler to extract shared dependencies.

In Webpack:

// webpack.config.js
optimization: {
  splitChunks: {
    chunks: 'all',
    cacheGroups: {
      vendor: {
        test: /[\\/]node_modules[\\/]/,
        name: 'vendors',
        chunks: 'all',
      },
    },
  },
}

This creates a separate vendors.chunk.js for third-party packages.

In Vite:

Vite automatically splits vendor code. You can customize it:

// vite.config.ts
export default defineConfig({
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          'vue-vendor': ['vue', 'vue-router'],
          'ui-lib': ['element-plus'],
        }
      }
    }
  }
})

This gives you fine-grained control over what goes where.


Gotchas and Best Practices

  • Don’t over-split: Too many small chunks increase HTTP overhead.
  • Avoid lazy loading everything: Only split large, infrequently used components.
  • Monitor bundle size: Use tools like Webpack Bundle Analyzer or Vite’s rollup-plugin-visualizer.
  • Preload critical chunks: Use <link rel="modulepreload"> (Vite) or webpack’s magic comments:
    import(/* webpackPreload: true */ './CriticalComponent')
  • Handle loading states gracefully: Use skeletons or spinners to improve perceived performance.

  • Code splitting, when done right, makes your React or Vue app feel fast and responsive. Start with route-based splitting, then optimize shared code and heavy components. The tools are built in — you just need to use them.

    Basically: split by route, lazy load what matters, and let your bundler handle the rest.

    The above is the detailed content of Code Splitting in Modern Web Apps: A Guide for React and Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Build international web applications using the FastAPI framework Build international web applications using the FastAPI framework Sep 29, 2023 pm 03:53 PM

Use the FastAPI framework to build international Web applications. FastAPI is a high-performance Python Web framework that combines Python type annotations and high-performance asynchronous support to make developing Web applications simpler, faster, and more reliable. When building an international Web application, FastAPI provides convenient tools and concepts that can make the application easily support multiple languages. Below I will give a specific code example to introduce how to use the FastAPI framework to build

How to develop a single-page web application using Golang How to develop a single-page web application using Golang Jun 05, 2023 am 09:51 AM

With the continuous development of the Internet, the demand for Web applications is also increasing. In the past, web applications were usually composed of multiple pages, but now more and more applications choose to use single page applications (SPA). Single-page applications are very suitable for mobile access, and users do not need to wait for the entire page to reload, which increases the user experience. In this article, we will introduce how to use Golang to develop SPA applications. What is a single page application? A single page application refers to a web application with only one HTML file. It uses Jav

How does PHP8 improve the performance of web applications through JIT compilation? How does PHP8 improve the performance of web applications through JIT compilation? Oct 18, 2023 am 08:04 AM

How does PHP8 improve the performance of web applications through JIT compilation? With the continuous development of Web applications and the increase in demand, improving the performance of Web applications has become one of the focuses of developers. As a commonly used server-side scripting language, PHP has always been loved by developers. The JIT (just-in-time compilation) compiler was introduced in PHP8, providing developers with a new performance optimization solution. This article will discuss in detail how PHP8 can improve the performance of web applications through JIT compilation, and provide specific code examples.

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Using Beego to develop web applications with microservice architecture Using Beego to develop web applications with microservice architecture Jun 23, 2023 am 08:39 AM

With the development of the Internet and the popularity of applications, the demand for Web applications has also continued to grow. In order to meet the needs of a large number of users, traditional web applications often face performance bottlenecks and scalability issues. In response to these problems, microservice architecture has gradually become a trend and solution for web application development. In the microservice architecture, the Beego framework has become the first choice of many developers. Its efficiency, flexibility, and ease of use are deeply loved by developers. This article will introduce the use of Beego framework to develop web applications with microservice architecture.

Vue3+TS+Vite development skills: How to use Vite for code splitting and on-demand loading Vue3+TS+Vite development skills: How to use Vite for code splitting and on-demand loading Sep 10, 2023 pm 12:57 PM

Vue3+TS+Vite development skills: How to use Vite for code splitting and on-demand loading. With the complexity of front-end engineering and the increase in project scale, code optimization has become a problem that every developer must face. An important aspect of this is code splitting and on-demand loading. Code splitting can divide the entire project code into small pieces, and on-demand loading can load the corresponding code when needed, effectively improving the performance and loading speed of web pages. In the Vue3+TypeScript project, we can

A complete guide to building web-based applications with PHP and SOAP A complete guide to building web-based applications with PHP and SOAP Jul 30, 2023 am 10:25 AM

A complete guide to building web-based applications using PHP and SOAP In today's Internet era, web-based applications have become an important tool for managing and interacting with data. As a powerful development language, PHP can be seamlessly integrated with other technologies, while SOAP (Simple Object Access Protocol), as an XML-based communication protocol, provides us with a simple, standard and extensible method to build Web services. . This article will provide you with

What are the advantages of using Java for web applications that need to run on different servers? What are the advantages of using Java for web applications that need to run on different servers? May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

See all articles