튜토리얼: Vite로 React 앱을 만드는 방법

DDD
풀어 주다: 2024-10-11 10:29:01
원래의
335명이 탐색했습니다.

1. 소개

JavaScript 프런트엔드 세계에는 새로운 프로젝트를 구축하고 최적화하기 위한 새로운 도구가 끊임없이 등장하고 있습니다. 사용자 인터페이스 구축을 위한 인기 있는 JavaScript 라이브러리인 React는 전통적으로 CRA(Create-React-App)와 결합되어 설정 및 개발을 단순화했습니다. 그러나 Vite라는 새로운 도구는 CRA에 대한 현대적인 대안을 제공하면서 속도와 효율성으로 인해 빠르게 주목을 받고 있습니다.

이 블로그 게시물에서는 먼저 Vite를 React 개발자에게 탁월한 선택으로 만드는 특정 기능을 제시한 다음 Create-React-App에 대해 자세히 살펴보겠습니다. 그런 다음 두 도구를 비교하여 각각의 도구를 언제 사용할지, 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는 웹 개발을 더 빠르고 효율적으로 만들기 위해 설계된 빌드 도구입니다. "Vite"라는 이름은 "빠르다"를 뜻하는 프랑스어에서 유래되었습니다. Vue.js 개발자인 Evan You가 만든 Vite는 Webpack과 같은 기존 번들러의 성능 제한을 해결하도록 설계되었습니다.

React, Vue, Svelte와 같은 널리 사용되는 프레임워크를 지원합니다. 유연성 덕분에 광범위한 프런트엔드 기술과 호환되므로 다양한 개발 요구 사항에 적응할 수 있습니다. 기본 ECMAScript 모듈과 최신 브라우저 기능을 활용하여 빠른 개발 환경을 제공합니다.

간단한 React 앱을 구축하든 복잡한 웹 애플리케이션을 구축하든 Vite는 시간을 절약할 수 있는 간소화된 환경을 제공합니다.

2.1 Vite가 만들어진 이유는 무엇입니까?

Webpack과 같은 기존 빌드 도구는 수년 동안 존재해 왔으며 개발자 커뮤니티에 좋은 서비스를 제공해 왔습니다. 그러나 웹 애플리케이션이 복잡해짐에 따라 개발 서버를 시작하고 변경 사항이 브라우저에 반영되는 것을 확인하는 데 걸리는 시간도 늘어났습니다.

다음 이미지는 기존 번들링 접근 방식을 설명합니다. 프로세스는 애플리케이션의 다양한 경로와 모듈에 연결되는 진입점으로 시작됩니다. 이러한 모든 구성 요소는 서버를 사용할 준비가 되기 전에 함께 번들로 제공됩니다. 이러한 사전 번들링은 시간이 많이 걸리며, 특히 애플리케이션이 커짐에 따라 개발 서버의 시작 시간이 길어집니다.

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)은 새로운 React 프로젝트 설정 프로세스를 단순화하기 위해 Facebook에서 개발한 인기 도구입니다. 이를 통해 개발자는 개발 환경을 수동으로 구성할 필요 없이 신속하게 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은 애플리케이션의 코드를 몇 개의 압축 파일로 묶습니다. 그런 다음 이러한 번들은 웹 서버를 통해 제공되므로 로컬 개발 서버를 통해 앱에 액세스할 수 있습니다.

  • 구성 필요 없음:
    CRA의 가장 큰 장점 중 하나는 완전한 기능을 갖춘 React 설정을 제공한다는 것입니다. CRA로 새 프로젝트를 생성하면 번들링을 위한 Webpack, 최신 JavaScript 트랜스파일을 위한 Babel, Linting을 위한 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 各ツールをいつ使用するか、いつ切り替えを検討するか

  1. Create-React-App を使用する場合:
  • 初心者向け:
    React やフロントエンド開発が初めての場合、CRA は優れた出発点となります。たとえば、単純なポートフォリオ Web サイトや個人のブログを構築している場合、構成ゼロのアプローチにより、基礎となるセットアップを気にせずに React の学習に集中できます。

  • 小規模から中規模のプロジェクトの場合:
    CRA は、パフォーマンスや構成の微調整よりもセットアップと使用の簡単さが重要な小規模プロジェクトに適しています。たとえば、CRA は企業の内部ダッシュボードや小規模な電子商取引サイトなどのプロジェクトに最適です。

  • 安定性のために:
    学校管理システムや組織の Web サイトなど、安定して広くサポートされているツールを必要とする長期プロジェクトを開発している場合、CRA の大規模なコミュニティと堅牢なドキュメントが信頼できる選択肢になります。頻繁に破壊的な変更が行われることを心配する必要はなく、コミュニティのサポートに頼ることができます。

  1. Vite を使用する場合:
  • 速度とパフォーマンスについて:
    ソーシャル メディア プラットフォームや複雑なデータ視覚化ダッシュボードなどの大規模なアプリケーションに取り組んでいる場合、Vite の速度が非常に重要になります。たとえば、アプリに多数のページやコンポーネントが含まれている場合、Vite の高速なビルド時間と効率的なホット モジュール交換 (HMR) により、開発中に更新を待つ時間を短縮できます。

  • 最新の開発プラクティスの場合:
    プロジェクトが ES モジュールの使用などの最新の JavaScript プラクティスに基づいている場合、または Svelte や TypeScript などの最先端のライブラリと統合している場合、Vite はワークフローを合理化できるすぐに使用できるサポートを提供します。例としては、最新の Web 標準と機能を常に最新の状態に保つ必要がある最新の SaaS プラットフォームを開発することが挙げられます。

  • 柔軟性の場合:
    特定の業界向けにカスタマイズされた CMS など、高度にカスタマイズされたアプリケーションを構築している場合、Vite のプラグイン システムとモジュラー アーキテクチャにより、Tailwind CSS、Preact、またはその他のニーズに合ったツールを簡単に統合できます。この柔軟性は、特定の要件を満たすためにデフォルト構成を大幅に調整する必要があるアプリケーションに特に役立ちます。

  1. CRA から Vite への切り替えを検討する場合:
  • プロジェクトとユーザーベースが大幅に成長し始めます:
    CRA から始めて、小さなプロジェクト管理ツールを構築することを想像してください。より多くの機能が追加され、ユーザー ベースが拡大すると、ビルド時間と開発サーバーの起動時間が大幅に増加することに気づく場合があります。この時点で、Vite に切り替えると、迅速な開発サイクルを維持でき、新しい機能をより効率的に追加できるようになります。

  • あなたは優れた開発者エクスペリエンスを求めています:
    開発中の迅速なフィードバックが重要であるリアルタイムの共同アプリに取り組んでいるとします。アプリの複雑さが増すと、CRA の速度が低下する可能性があります。 Vite に切り替えると、サーバーの起動と HMR の高速化のメリットが得られ、開発プロセスの応答性が向上します。

  • 最新のツールで一歩先を行くには:
    最新の Web 開発実践を紹介する必要があるチュートリアル サイトを管理している場合は、CRA から Vite への移行が有益になる可能性があります。このスイッチを使用すると、最新のツールと手法をデモンストレーションできるようになり、将来を見据えた視聴者にとってコンテンツの関連性と有益性を維持できるようになります。

5. Vite と React の入門

このセクションでは、React で Vite を使用するための 2 つの異なるアプローチを説明します。新しいプロジェクトを開始する場合でも、既存の Create-React-App (CRA) プロジェクトを Vite にアップグレードすることを検討している場合でも、私たちはあなたをサポートします。

5.1 前提条件

このチュートリアルは、React と JavaScript の基本を理解していることを前提としています。開始するには、マシンに Node.js と NPM がインストールされていることを確認してください。

5.2 Vite を使用して React プロジェクトをセットアップする

Vite を使用して新しい React プロジェクトを開始するのは迅速かつ簡単です。完全なコードを確認したい場合は、GitHub の React Application with Vite リポジトリをチェックしてください。

開始方法は次のとおりです:

1.新しい Vite プロジェクトを作成します

まず、ターミナルを開き、次のコマンドを実行して、React をテンプレートとして新しい Vite プロジェクトを作成します。

npm create vite@latest my-react-vite-app -- --template react
로그인 후 복사

2.プロジェクト ディレクトリに移動します

プロジェクトが作成されたら、プロジェクト ディレクトリに移動します。

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 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!