ホームページ > 記事 > ウェブフロントエンド > React プロジェクトで遅延読み込みとコード分割を実装するためのステップバイステップ ガイド
Here’s a step-by-step guide to implementing lazy loading and code splitting in a React project. We'll create a simple application with two routes, loading components lazily.
If you haven’t already, create a new React app using Create React App:
npx create-react-app lazy-loading-example cd lazy-loading-example
Install react-router-dom for routing:
npm install react-router-dom
Home.js
import React from 'react'; const Home = () => { return <h2>Home Page</h2>; }; export default Home;
About.js
import React from 'react'; const About = () => { return <h2>About Page</h2>; }; export default About;
Now, modify your App.js file to implement lazy loading and routing:
import React, { Suspense } from 'react'; import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom'; // Lazy load components const Home = React.lazy(() => import('./components/Home')); const About = React.lazy(() => import('./components/About')); function App() { return ( <Router> <nav> <ul> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About</Link> </li> </ul> </nav> <Suspense fallback={<div>Loading...</div>}> <Switch> <Route path="/about" component={About} /> <Route path="/" component={Home} /> </Switch> </Suspense> </Router> ); } export default App;
Now, run your application to see it in action:
npm start
You can further enhance your setup by:
If you need more specific features or additional help, let me know!
以上がReact プロジェクトで遅延読み込みとコード分割を実装するためのステップバイステップ ガイドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。