最新のWebアプリでのコード分割:React and Vueのガイド
代码分割对现代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('./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’smagic 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.
以上が最新のWebアプリでのコード分割:React and Vueのガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ホットAIツール

Undress AI Tool
脱衣画像を無料で

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

ドリームウィーバー CS6
ビジュアル Web 開発ツール

SublimeText3 Mac版
神レベルのコード編集ソフト(SublimeText3)

FastAPI フレームワークを使用して国際的な Web アプリケーションを構築します。FastAPI は、Python 型の注釈と高性能の非同期サポートを組み合わせた高性能 Python Web フレームワークで、Web アプリケーションの開発をよりシンプル、高速、信頼性の高いものにします。国際的な Web アプリケーションを構築する場合、FastAPI は、アプリケーションで複数の言語を簡単にサポートできるようにする便利なツールと概念を提供します。以下に、FastAPI フレームワークを使用してビルドする方法を紹介する具体的なコード例を示します。

インターネットの継続的な発展に伴い、Web アプリケーションの需要も増加しています。以前は、Web アプリケーションは通常複数のページで構成されていましたが、現在ではシングル ページ アプリケーション (SPA) を使用するアプリケーションが増えています。シングルページ アプリケーションはモバイル アクセスに非常に適しており、ユーザーはページ全体がリロードされるまで待つ必要がないため、ユーザー エクスペリエンスが向上します。この記事では、Golang を使用して SPA アプリケーションを開発する方法を紹介します。シングル ページ アプリケーションとは何ですか? シングル ページ アプリケーションとは、HTML ファイルが 1 つだけ含まれる Web アプリケーションを指します。 Javaを使用します

PHP8 は JIT コンパイルを通じて Web アプリケーションのパフォーマンスをどのように向上させますか? Web アプリケーションの継続的な開発と需要の増加に伴い、Web アプリケーションのパフォーマンスの向上が開発者の焦点の 1 つになっています。一般的に使用されるサーバーサイド スクリプト言語として、PHP は常に開発者に愛されてきました。 JIT (ジャストインタイム コンパイル) コンパイラーは PHP8 で導入され、開発者に新しいパフォーマンス最適化ソリューションを提供します。この記事では、PHP8 が JIT コンパイルを通じて Web アプリケーションのパフォーマンスを向上させる方法について詳しく説明し、具体的なコード例を示します。

WebアプリケーションにおけるMySQLの主な役割は、データを保存および管理することです。 1.MYSQLは、ユーザー情報、製品カタログ、トランザクションレコード、その他のデータを効率的に処理します。 2。SQLクエリを介して、開発者はデータベースから情報を抽出して動的なコンテンツを生成できます。 3.MYSQLは、クライアントサーバーモデルに基づいて機能し、許容可能なクエリ速度を確保します。

インターネットの発展とアプリケーションの普及に伴い、Web アプリケーションの需要も成長し続けています。多数のユーザーのニーズを満たすために、従来の Web アプリケーションはパフォーマンスのボトルネックやスケーラビリティの問題に直面することがよくあります。これらの問題に対応して、マイクロサービス アーキテクチャが徐々に Web アプリケーション開発のトレンドおよびソリューションになってきました。マイクロサービス アーキテクチャでは、Beego フレームワークが多くの開発者の最初の選択肢となり、その効率性、柔軟性、使いやすさが開発者に深く愛されています。この記事では、Beego フレームワークを使用してマイクロサービス アーキテクチャで Web アプリケーションを開発する方法を紹介します。

Vue3+TS+Vite 開発スキル: コード分割とオンデマンド読み込みに Vite を使用する方法 フロントエンド エンジニアリングの複雑化とプロジェクト規模の増大に伴い、コードの最適化はすべての開発者が直面しなければならない問題となっています。この重要な側面は、コード分割とオンデマンド読み込みです。コード分割によりプロジェクト コード全体を小さな部分に分割し、オンデマンド読み込みにより必要なときに対応するコードを読み込むことができるため、Web ページのパフォーマンスと読み込み速度が効果的に向上します。 Vue3+TypeScript プロジェクトでは、次のことができます。

Javaは、クロスサーバーWebアプリケーションの開発に適しています。 1)Javaの「Write and、Run Averywhere」哲学は、JVMをサポートするあらゆるプラットフォームでコードを実行します。 2)Javaには、開発プロセスを簡素化するために、SpringやHibernateなどのツールを含む豊富なエコシステムがあります。 3)Javaは、パフォーマンスとセキュリティにおいて優れたパフォーマンスを発揮し、効率的なメモリ管理と強力なセキュリティ保証を提供します。

PHP と SOAP を使用して Web ベースのアプリケーションを構築するための完全ガイド 今日のインターネット時代において、Web ベースのアプリケーションはデータを管理し、データと対話するための重要なツールとなっています。 PHP は強力な開発言語として他のテクノロジーとシームレスに統合でき、XML ベースの通信プロトコルである SOAP (Simple Object Access Protocol) は、Web サービスを構築するためのシンプルで標準的かつ拡張可能な方法を提供します。この記事では、次のことを提供します
