ホームページ  >  記事  >  ウェブフロントエンド  >  チュートリアル: Vite を使用して React アプリを作成する方法

チュートリアル: Vite を使用して React アプリを作成する方法

DDD
DDDオリジナル
2024-10-11 10:29:01335ブラウズ

1. はじめに

JavaScript フロントエンドの世界では、プロジェクトを構築および最適化するための新しいツールが常に登場しています。ユーザー インターフェイスを構築するための人気のある JavaScript ライブラリである React は、セットアップと開発を簡素化するために、伝統的に Create-React-App (CRA) と組み合わせられてきました。ただし、Vite と呼ばれる新しいツールは、その速度と効率性により急速に注目を集めており、CRA の最新の代替手段を提供しています。

このブログ投稿では、Vite が React 開発者にとって優れた選択肢となる具体的な機能を紹介することから始め、次に Create-React-App について詳しく見ていきます。その後、2 つのツールを比較して、それぞれをいつ使用するか、いつ CRA から Vite に切り替えるかを決定するのに役立ちます。

新しい React プロジェクトを開始する場合でも、既存のプロジェクトの移行を検討している場合でも、プロセスをガイドし、ニーズに最適なツールを選択できるようにお手伝いします。さらに、Vite と React のセットアップを最大限に活用したい人向けに、高度な構成と最適化のテクニックについても説明します。

この投稿を終えるまでに、次の重要な質問に対する答えが得られるでしょう:

  1. React 開発に最適な Vite のユニークな機能は何ですか?

  2. パフォーマンス、構成、柔軟性の点で Create-React-App と Vite を比較するとどうですか?

  3. Create-React-App を使い続ける必要があるのはどのような場合ですか?また、Vite に切り替える方が良いのはどのような場合ですか?

  4. Vite で新しい React プロジェクトをセットアップするにはどのような手順がありますか?

  5. 既存の Create-React-App プロジェクトを Vite に移行するにはどうすればよいですか?

  6. Vite と React のセットアップを最大限に活用するには、どのような高度な構成および最適化テクニックを適用できますか?

2. Viteとは何ですか?

Tutorial: How to Create a React App with Vite

Vite は、Web 開発をより迅速かつ効率的に行うために設計されたビルド ツールです。名前の「Vite」はフランス語で「速い」を意味する言葉に由来しています。 Vue.js の開発者と同じ開発者である Evan You によって作成された Vite は、Webpack などの従来のバンドラーのパフォーマンス制限に対処するように設計されました。

React、Vue、Svelte などの人気のあるフレームワークのサポートを提供します。その柔軟性により、幅広いフロントエンド テクノロジーと互換性があり、さまざまな開発ニーズに確実に適応できます。ネイティブ ECMAScript モジュールと最新のブラウザ機能を活用して、高速な開発環境を提供します。

単純な React アプリを構築しているか複雑な Web アプリケーションを構築しているかに関係なく、Vite は時間を節約できる合理化されたエクスペリエンスを提供します。

2.1 Vite はなぜ作成されたのですか?

Webpack のような従来のビルド ツールは何年も前から存在しており、開発者コミュニティに十分に貢献してきました。ただし、Web アプリケーションが複雑になるにつれて、開発サーバーを起動して、ブラウザーに変更が反映されるのを確認するのにかかる時間も増加しました。

次の図は、従来のバンドル手法を説明しています。このプロセスは、アプリケーションのさまざまなルートやモジュールに接続するエントリ ポイントから始まります。これらすべてのコンポーネントは、サーバーを使用する準備が整う前にまとめてバンドルされます。この事前のバンドルには時間がかかり、特にアプリケーションが成長するにつれて、開発サーバーの起動時間が長くなります。

Tutorial: How to Create a React App with Vite

Vite は、開発中にアプリケーションの構築と提供に異なるアプローチを採用しています。すべてを事前にバンドルするのではなく、サーバーはほぼ瞬時に準備が整い、ブラウザーは必要なときに必要な特定のモジュールのみを要求します。これは、ネイティブ ES モジュール (ESM) サポートによって可能になり、動的なインポートが可能になり、コード分割が可能になり、常に処理する必要があるコードの量が削減されます。 Vite は必要なものだけを提供することで、フィードバック ループをより高速化し、開発者がより効率的に作業できるようにします。

Tutorial: How to Create a React App with Vite

2.2 Vite の主な機能

Vite の主要な機能は次のとおりです:

  • インスタントサーバー起動:
    従来のツールでは、特に大規模なプロジェクトの場合、開発サーバーの起動に時間がかかることがあります。ただし、Vite はほぼ瞬時に起動します。これは、プロジェクト全体ではなく、現在作業しているコードのみを変換することによって行われます。これにより、開発エクスペリエンスがよりスムーズになり、応答性が向上します。

  • 超高速ホットモジュール交換 (HMR):
    ホット モジュール交換 (HMR) を使用すると、ブラウザを更新することなく、コード変更の結果をリアルタイムで確認できます。 Vite の HMR は、アプリケーション全体ではなく、変更された特定のモジュールのみを更新するため、信じられないほど高速です。この即時のフィードバック ループにより、開発プロセスがより効率化されます。

  • ネイティブ ES モジュールのサポート:
    Vite は、最新のブラウザに組み込まれているネイティブ ES モジュール サポートを活用します。 (従来のツールのように) コードベース全体をいくつかの大きなファイルにバンドルする代わりに、Vite は各モジュールを個別のファイルとして提供します。これにより、複雑な変換の必要性が減り、初期ロードとその後の更新の両方が高速化されます。

  • ロールアップを使用した最適化されたビルド プロセス:
    Vite は生産面でも強力です。デプロイの準備ができたら、Vite は最新のモジュール バンドラーである Rollup を使用してコードを効率的にバンドルします。これは、高速な開発と最適化された運用ビルドの両方の長所を活用できることを意味します。

  • vite.config.js の柔軟な構成:
    Vite は高度にカスタマイズ可能です。簡単な構成ファイル (vite.config.js) を使用すると、プロジェクトのニーズに合わせて設定を簡単に調整できます。環境変数の設定、パス エイリアスの設定、プラグインの追加が必要な場合でも、Vite を使用するとそれが簡単になります。

  • ネイティブ TypeScript サポート:
    React と Vite は両方とも TypeScript をネイティブにサポートしているため、コードに静的型付けを簡単に組み込むことができます。 TypeScript を使用すると、開発プロセスの早い段階でエラーを検出し、コードの保守性が向上します。

3. Create-React-App とは何ですか?

Create-React-App (CRA) は、Facebook が開発した人気のツールで、新しい React プロジェクトのセットアップ プロセスを簡素化します。これにより、開発者は開発環境を手動で構成する必要がなく、React アプリケーションの構築をすぐに開始できます。

3.1 Create-React-App はなぜ作成されたのですか?

CRA が登場する前は、React プロジェクトを設定するにはさまざまなツールを設定する必要があり、特に React を初めて使用する人にとっては困難な作業になる可能性がありました。この課題に対処するために、CRA はゼロ構成セットアップを提供するソリューションとして 2016 年に導入されました。このツールにより、開発者はビルド ツールや構成の複雑さを気にすることなく、すぐに React コードの作成に取り掛かることができました。

CRA は、プロジェクトのセットアップを合理化し、開発環境に一貫性をもたらし、チームが効果的に共同作業しやすくなったため、すぐに React 開発者にとっての標準ツールになりました。

3.2 Create-React-App の主な機能

CRA の主要な機能は次のとおりです:

  • Webpack を使用した依存関係ツリーの作成:
    CRA は Webpack を使用してプロジェクトの Index.js ファイルを分析します。これはアプリケーションのエントリ ポイントとして機能します。次に、Webpack はプロジェクトに必要なすべてのモジュールをリンクして依存関係のツリーを作成します。この自動化されたプロセスにより、アプリケーションに必要なすべてのリソースがバンドルされることが保証されます。

  • Babel によるコードのトランスパイル:
    依存関係ツリーが構築されると、CRA は Babel を使用して、最新の JavaScript をより幅広いブラウザーと互換性のあるバージョンにトランスパイルします。この手順により、最新の JavaScript 機能をサポートしているかどうかに関係なく、アプリがさまざまな環境でスムーズに実行できるようになります。

  • コードのバンドルと提供:
    トランスパイル後、Webpack はアプリケーションのコードをいくつかの圧縮ファイルにバンドルします。これらのバンドルは Web サーバーを通じて提供され、ローカル開発サーバー経由でアプリにアクセスできるようになります。

  • 構成は必要ありません:
    CRA の最大の利点の 1 つは、完全に機能する React セットアップを提供することです。 CRA で新しいプロジェクトを作成すると、バンドル用の Webpack、最新の JavaScript のトランスパイル用の Babel、lint 用の ESLint など、必要なものがすべて自動的にセットアップされます。これは、環境の構成に時間を費やすことなく、すぐにコーディングを開始できることを意味します。

4. Create-React-App から Vite への切り替えを検討する理由は何ですか?

このセクションでは、構成、パフォーマンス、サポート、機能といったいくつかの主要な領域にわたって Vite と CRA を比較し、CRA から Vite に切り替えるのが適切な時期を判断するのに役立ちます。

4.1 比較: Vite と Create-React-App

Create-React-App Vite
Configuration Zero Configuration: CRA is known for its zero-configuration setup. You can create a new React project with a single command, and everything is ready to go, including Webpack, Babel, and ESLint. Simple and Flexible Configuration: Vite offers a straightforward setup process, but with greater flexibility. Vite's configuration is minimal and easy to customize through a vite.config.js file. You can add plugins, configure build options, and set up environment variables with ease. This makes Vite a better choice for projects where you anticipate needing custom configurations.
Performance Traditional Bundling: CRA relies on Webpack for bundling your application. While Webpack is powerful, it can be slow, especially as your project grows. The initial server start-up time and the time it takes to reflect changes in the browser can increase significantly, leading to longer development cycles. (Traditional Bundling Process) Instant Development with ES Modules: Vite’s approach to development is centered around speed. By using native ES modules, Vite eliminates the need for bundling during development, resulting in nearly instant server start times. Changes to your code are reflected immediately in the browser, thanks to Vite’s lightning-fast HMR. For larger projects, the performance difference is especially noticeable. (Vite's Process)
Support and Ecosystem Mature Ecosystem: CRA has been around for several years and has a large, active community. This means there is a wealth of tutorials, plugins, and third-party tools available. Additionally, because CRA is backed by Facebook, it has strong support and regular updates. For developers who prefer stability and extensive community resources, CRA remains a solid choice. Growing Ecosystem: While Vite is newer, it has quickly gained traction in the developer community. Its plugin ecosystem is expanding rapidly, with support for various frameworks and tools. Vite is also highly compatible with modern JavaScript features and has a growing number of contributors.
Features - All-in-one solution
- Built-in testing tools like Jest and React Testing Library
- Built-in service workers for Progressive Web Apps (PWAs)
- Environment variable management
- Modular and extensible
- Support for JSX and TypeScript
- Plugin-Based Architecture
- Fast Development Server
- Environment Variable Management

4.2 Quand utiliser chaque outil et quand envisager de changer

  1. Quand utiliser Create-React-App :
  • Pour les débutants :
    Si vous êtes nouveau dans React ou dans le développement front-end, CRA est un excellent point de départ. Par exemple, si vous créez un simple site Web de portfolio ou un blog personnel, son approche sans configuration vous permet de vous concentrer sur l'apprentissage de React sans vous soucier de la configuration sous-jacente.

  • Pour les projets petits à moyens :
    CRA est bien adapté aux petits projets où la simplicité de configuration et d'utilisation est plus importante que le réglage fin des performances ou de la configuration. Par exemple, CRA est parfait pour des projets comme le tableau de bord interne d’une entreprise ou un petit site de commerce électronique.

  • Pour la stabilité :
    Si vous développez un projet à long terme qui nécessite un outil stable et largement pris en charge, comme un système de gestion scolaire ou le site Web d'une organisation, la vaste communauté et la documentation robuste de CRA en font un choix fiable. Vous n'aurez pas à vous soucier des changements fréquents et vous pouvez compter sur le soutien de la communauté.

  1. Quand utiliser Vite :
  • Pour la vitesse et les performances :
    Si vous travaillez sur une application à grande échelle, telle qu'une plateforme de médias sociaux ou un tableau de bord de visualisation de données complexe, la vitesse de Vite devient critique. Par exemple, si votre application contient de nombreuses pages ou composants, les temps de construction rapides de Vite et le remplacement efficace des modules à chaud (HMR) peuvent réduire le temps que vous passez à attendre les mises à jour pendant le développement.

  • Pour les pratiques de développement modernes :
    Si votre projet est basé sur des pratiques JavaScript modernes telles que l'utilisation de modules ES, ou si vous intégrez des bibliothèques de pointe comme Svelte ou utilisez TypeScript, Vite fournit une prise en charge prête à l'emploi qui peut rationaliser votre flux de travail. Un exemple serait de développer une plate-forme SaaS moderne sur laquelle vous devez rester à jour avec les dernières normes et fonctionnalités Web.

  • Pour la flexibilité :
    Si vous créez une application hautement personnalisée, telle qu'un CMS adapté à un secteur spécifique, le système de plugins et l'architecture modulaire de Vite vous permettent d'intégrer facilement des outils tels que Tailwind CSS, Preact ou d'autres qui répondent à vos besoins. Cette flexibilité est particulièrement utile pour les applications où la configuration par défaut nécessite des ajustements importants pour répondre à des exigences spécifiques.

  1. Quand envisager de passer de CRA à Vite :
  • Votre projet et votre base d'utilisateurs commencent à croître de manière significative :
    Imaginez commencer avec CRA pour créer un petit outil de gestion de projet. À mesure que de nouvelles fonctionnalités sont ajoutées et que la base d'utilisateurs augmente, vous remarquerez peut-être que les temps de construction et les temps de démarrage du serveur de développement augmentent considérablement. À ce stade, passer à Vite peut vous aider à maintenir un cycle de développement rapide, vous permettant d'ajouter de nouvelles fonctionnalités plus efficacement.

  • Vous recherchez une superbe expérience de développeur :
    Supposons que vous travailliez sur une application collaborative en temps réel pour laquelle un retour rapide pendant le développement est crucial. L'ARC peut ralentir à mesure que la complexité de votre application augmente. En passant à Vite, vous pouvez bénéficier de démarrages de serveur plus rapides et de son HMR, ce qui se traduit par un processus de développement plus réactif.

  • Pour garder une longueur d'avance avec des outils modernes :
    Si vous gérez un site de didacticiels qui doit présenter les dernières pratiques de développement Web, la transition de CRA vers Vite pourrait être bénéfique. Ce changement vous permet de démontrer des outils et des méthodes modernes, aidant votre contenu à rester pertinent et informatif pour un public tourné vers l'avenir.

5. Premiers pas avec Vite et React

Dans cette section, nous vous présenterons deux approches différentes pour utiliser Vite avec React. Que vous démarriez un nouveau projet ou que vous cherchiez à mettre à niveau un projet Create-React-App (CRA) existant vers Vite, nous avons ce qu'il vous faut.

5.1 Conditions préalables

Ce tutoriel suppose que vous possédez une compréhension de base de React et de JavaScript. Pour commencer, assurez-vous que Node.js et NPM sont installés sur votre machine.

5.2 Configurer un projet React à l'aide de Vite

Démarrer un nouveau projet React avec Vite est rapide et simple. Si vous souhaitez voir le code complet, consultez notre application React avec référentiel Vite sur GitHub.

Voici comment commencer :

1. Créer un nouveau projet Vite

Tout d'abord, ouvrez votre terminal et exécutez la commande suivante pour créer un nouveau projet Vite avec React comme modèle :

npm create vite@latest my-react-vite-app -- --template react

2. Accédez au répertoire de votre projet

Une fois le projet créé, accédez au répertoire du projet :

cd my-react-vite-app

3. Select a Variant

TypeScript

4. Install Dependencies

Next, install the required dependencies by running:

npm install

5. Start the Development Server

Once the installation is complete, start the development server:

npm run dev

Your project should now be running locally, and you can see it in action by opening your browser and navigating to http://localhost:5173/
Tutorial: How to Create a React App with Vite
And that’s it! You’ve successfully set up a new React project using Vite.

5.3 Migrate an existing CRA Project to Vite

We will guide you through migrating an existing Create-React-App (CRA) project to Vite. If you want to see the complete code, check out our Migrate CRA to Vite repository on GitHub.To make the migration process clear and accessible, we'll start by creating a new CRA project using npx, and then proceed with the migration to Vite.

Npx is a command-line tool that comes with npm (version 5.2.0 and above). While npm is used to install packages globally or locally, npx allows you to execute packages without installing them permanently. For example, when you run npx create-react-app my-app, npx temporarily downloads and executes the create-react-app package to generate a new React project.

1. Create a New React App with Create-React-App (CRA)

If you don't already have an existing CRA project, you can create one using npx. This will give us a starting point for the migration process.

Open your terminal and run the following command to create a new React app using CRA:

npx create-react-app my-cra-app

This command will set up a new React project named my-cra-app with all the default configurations provided by CRA.

2. Navigate to the project directory once the setup is complete:

cd my-cra-app

3. Run the development server to ensure everything is set up correctly:

npm start

This command will start the CRA development server, and you can see your new React app running at http://localhost:3000.
Tutorial: How to Create a React App with Vite
At this point, you have a working CRA project that we will now migrate to Vite.

4. Install Vite

Stop the CRA development server if it's running, and then install Vite as a dependency:

npm install vite

5. Install the Vite React plugin

It will handle React-specific features:

npm install @vitejs/plugin-react

6. Create index.html

Create the index.html file in the root of your project.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>React Vite Migration</title>
  </head>
  <body>
    <p>Hello Vite!</p>
  </body>
</html>

7. Create vite.config.js

In the root directory of your project, create a file named vite.config.js and add the following configuration:

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
  plugins: [react()],
});

This file configures Vite to work with React, enabling JSX and other React-specific features.

8. Update package.json Scripts

Open your package.json file and replace the existing CRA scripts with Vite equivalents:

"scripts": {
    "dev": "vite",
    "build": "vite build",
    "serve": "vite preview"
  },

The dev script starts the Vite development server, build creates a production build and serve allows you to preview the build locally.

9. Start the Development Server

npm run dev

Your project should now be running locally, and you can see it in action by opening your browser and navigating to http://localhost:5174

Tutorial: How to Create a React App with Vite

Once you’ve set up your React project with Vite, it’s time to add some advanced configuration and optimization techniques. This section will help you customize your Vite setup to fit your project’s specific needs and ensure your application is optimized for production.

6.Advanced Configuration and Optimization

The vite.config.js file is where you can customize your Vite setup to suit the requirements of your project. Let’s go through the key areas you might want to adjust and how to do it.

6.1 Adding and Configuring Plugins

Vite has a powerful plugin system that allows you to extend its functionality. For example, if you need to add support for additional features like TypeScript, you can include relevant plugins in the plugins array.

Here’s an example:

import react from "@vitejs/plugin-react";

import tsconfigPaths from "vite-tsconfig-paths";

export default defineConfig({
  plugins: [react(), tsconfigPaths()],
});

6.2 Adding Path Aliases

Path Aliases reduces the need for long relative paths and makes your code easier to navigate.

First, configure path aliases in Vite by modifying the vite.config.js file:

import path from "path";

resolve: {
    alias: {
        "@components": path.resolve(__dirname, "src/components"),
        "@assets": path.resolve(__dirname, "src/assets"),
        "@utils": path.resolve(__dirname, "src/utils"),
    },
}

These aliases allow you to import modules using cleaner paths, such as:

import Header from '@components/Header';

6.3 Customizing the Development Server

You can customize the development server to fit your needs. For example, you might want to change the default port.

Here’s the relevant configuration:

server: {

    port: 3000, // Default port is 5173, but you can change it to 3000 or any other port

    open: true, // Open the browser automatically

}

6.4 Configuring the Build Process

The build section in vite.config.js allows you to customize how your project is bundled for production. You can specify the output directory, enable source maps for debugging, and more.

build: {
    outDir: 'dist', // Customize the output directory
    sourcemap: true, // Generate source maps for easier debugging
    minify: 'esbuild', // Use esbuild for minification (default is Terser)
},

6.5 Optimizing for Production

When preparing your project for production, there are several strategies you can use to optimize your build output:

  • Lazy Loading Components
    For large React applications, consider using React’s lazy() and Suspense to load components only when they’re needed. This reduces the initial load time and improves the perceived performance of your application.

  • Splitting Large Components:
    Break down large components into smaller, self-contained components that can be lazy loaded. This minimizes the amount of JavaScript that needs to be loaded initially.

  • Analyzing the Bundle Size
    Use tools like rollup-plugin-visualizer to analyze your bundle size and see which parts of your application are taking up the most space. This can help you identify optimization opportunities.

7. Conclusion

Vite and Create-React-App (CRA) both serve as powerful tools for React development, each with its unique strengths. CRA is an excellent starting point for beginners and small to medium-sized projects, offering a zero-configuration setup that lets you dive straight into coding. However, as your project grows, CRA's performance can start to lag, and its rigid configuration may feel limiting. This is where Vite shines.

Vite offers lightning-fast development with instant server start and quick Hot Module Replacement (HMR), making it ideal for larger projects and developers seeking more control. With modern tooling, simplified yet flexible configuration, and optimized production builds, Vite provides a streamlined and future-proof development experience. Whether you’re starting a new project or considering a switch, Vite offers the speed and flexibility to enhance your workflow, making it a compelling choice for modern React development.

以上がチュートリアル: Vite を使用して React アプリを作成する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。