目录
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
首页 web前端 H5教程 现代网络应用中的代码分裂:React和Vue指南

现代网络应用中的代码分裂:React和Vue指南

Jul 31, 2025 pm 12:35 PM
web应用 代码分割

代码分割对现代Web性能至关重要,能显着提升加载速度和用户体验。 1. 在React中使用React.lazy和Suspense实现路由级代码分割,仅在需要时加载组件,并通过Suspense显示加载状态;2. Vue中使用defineAsyncComponent或动态import()实现异步组件加载,支持错误处理和延迟加载;3. 路由级分割是最有效的起点,因与用户导航一致且工具链自动支持;4. 通过Webpack或Vite配置提取共享依赖,避免重复加载第三方库;5. 避免过度分割、合理使用预加载、监控包体积并优雅处理加载状态,以实现最佳性能。正确实施代码分割可让React或Vue应用更快速响应。

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(&#39;./components/CommentSection&#39;));

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 &#39;vue&#39;;
import { createRouter } from &#39;vue-router&#39;;

const HomePage = () => import(&#39;../views/HomePage.vue&#39;);
const AboutPage = defineAsyncComponent(() =>
  import(&#39;../views/AboutPage.vue&#39;)
);

const routes = [
  { path: &#39;/&#39;, component: HomePage },
  { path: &#39;/about&#39;, 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 (eg, error handling, loading delays):
 const AsyncComponent = defineAsyncComponent({
  loader: () => import(&#39;./HeavyComponent.vue&#39;),
  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" */ &#39;./pages/AboutPage&#39;));

In Vue with Vite, use:

 () => import(&#39;../views/About.vue&#39;).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 (eg, Lodash, date-fns). Use your bundler to extract shared dependencies.

In Webpack:

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

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: {
          &#39;vue-vendor&#39;: [&#39;vue&#39;, &#39;vue-router&#39;],
          &#39;ui-lib&#39;: [&#39;element-plus&#39;],
        }
      }
    }
  }
})

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 */ &#39;./CriticalComponent&#39;)
  • 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.

    以上是现代网络应用中的代码分裂:React和Vue指南的详细内容。更多信息请关注PHP中文网其他相关文章!

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

热门话题

PHP教程
1535
276
使用FastAPI框架构建国际化的Web应用 使用FastAPI框架构建国际化的Web应用 Sep 29, 2023 pm 03:53 PM

使用FastAPI框架构建国际化的Web应用FastAPI是一个高性能的PythonWeb框架,它结合了Python类型注解和性能较好的异步支持,使得开发Web应用变得更加简单、快速和可靠。在构建一个国际化的Web应用时,FastAPI提供了方便的工具和理念,可以使得应用能够轻松支持多种语言。下面我将给出一个具体的代码示例,介绍如何使用FastAPI框架构

如何使用Golang开发单页面Web应用 如何使用Golang开发单页面Web应用 Jun 05, 2023 am 09:51 AM

随着互联网的不断发展,Web应用的需求也与日俱增。在过去,Web应用通常都是由多个页面组成的,但是现在越来越多的应用选择采用单页面应用(SPA)。单页面应用非常适合移动端的访问,而且用户无需等待页面的整个重新加载,增加了用户的体验。在本文中,将介绍如何使用Golang开发SPA应用。什么是单页面应用单页面应用是指只有一个HTML文件的Web应用。它使用Jav

PHP8如何通过JIT编译提升Web应用的性能? PHP8如何通过JIT编译提升Web应用的性能? Oct 18, 2023 am 08:04 AM

PHP8如何通过JIT编译提升Web应用的性能?随着Web应用的不断发展和需求的增加,提升Web应用的性能成为了开发者关注的焦点之一。PHP作为一种常用的服务器端脚本语言,一直以来都备受开发者喜爱。而PHP8中引入了JIT(即时编译)编译器,为开发者提供了一个全新的性能优化方案。本文将详细讨论PHP8如何通过JIT编译提升Web应用的性能,并提供具体的代码示

MySQL的角色:Web应用程序中的数据库 MySQL的角色:Web应用程序中的数据库 Apr 17, 2025 am 12:23 AM

MySQL在Web应用中的主要作用是存储和管理数据。1.MySQL高效处理用户信息、产品目录和交易记录等数据。2.通过SQL查询,开发者能从数据库提取信息生成动态内容。3.MySQL基于客户端-服务器模型工作,确保查询速度可接受。

使用Beego开发微服务架构的Web应用 使用Beego开发微服务架构的Web应用 Jun 23, 2023 am 08:39 AM

随着互联网的发展和应用的普及,Web应用的需求也随之不断增长。而为了满足大量用户的需求,传统的Web应用往往会面临性能瓶颈和可扩展性问题。针对这些问题,微服务架构逐渐成为了Web应用开发的一种趋势和解决方案。而在微服务架构中,Beego框架成为了很多开发者的首选,其高效、灵活、易用的特点深受开发者的喜爱。本文将介绍使用Beego框架开发微服务架构的Web应用

Vue3+TS+Vite开发技巧:如何利用Vite进行代码分割和按需加载 Vue3+TS+Vite开发技巧:如何利用Vite进行代码分割和按需加载 Sep 10, 2023 pm 12:57 PM

Vue3+TS+Vite开发技巧:如何利用Vite进行代码分割和按需加载随着前端工程的复杂化和项目规模的增大,代码的优化成为了每个开发者必须要面对的问题。而其中的一个重要方面就是代码分割和按需加载。代码分割可以将整个项目的代码分割成小块,按需加载可以在需要的时候再去加载相应的代码,有效地提高网页的性能和加载速度。在Vue3+TypeScript项目中,我们可

将Java用于需要在不同服务器上运行的Web应用程序的优点是什么? 将Java用于需要在不同服务器上运行的Web应用程序的优点是什么? May 03, 2025 am 12:13 AM

Java适合开发跨服务器web应用。1)Java的“一次编写,到处运行”哲学使其代码可在任何支持JVM的平台上运行。2)Java拥有丰富的生态系统,包括Spring和Hibernate等工具,简化开发过程。3)Java在性能和安全性方面表现出色,提供高效的内存管理和强大的安全保障。

利用PHP和SOAP构建基于Web的应用程序的完整指南 利用PHP和SOAP构建基于Web的应用程序的完整指南 Jul 30, 2023 am 10:25 AM

利用PHP和SOAP构建基于Web的应用程序的完整指南在当今互联网的时代,基于Web的应用程序已经成为了管理和交互数据的重要工具。PHP作为一种强大的开发语言,可以与其他技术进行无缝集成,而SOAP(SimpleObjectAccessProtocol)作为一种基于XML的通信协议,为我们提供了一种简单、标准和可扩展的方法来构建Web服务。本文将为您提

See all articles