React와 함께 Vite를 사용하기 위한 초보자 가이드

王林
풀어 주다: 2024-09-05 22:33:33
원래의
880명이 탐색했습니다.

A beginners guide to using Vite with React

소개

새 React 프로젝트를 시작할 때 올바른 도구를 선택하면 작업 흐름에 큰 영향을 미칠 수 있습니다. Webpack과 같은 도구는 수년간 널리 사용되었지만 Vite와 같은 최신 옵션은 더 빠르고 효율적인 대안을 제공합니다.

Evan You(Vue.js 창시자)가 개발한 Vite는 매우 빠른 개발 환경을 제공하도록 설계되었습니다. 이는 기본 ES 모듈을 통해 파일을 제공하고 최적화된 개발 서버를 사용하여 이를 수행합니다. 그 결과 서버 시작 시간이 더 빨라지고 개발 속도가 빨라졌습니다.

사용자 인터페이스 구축을 위한 가장 인기 있는 라이브러리 중 하나인 React는 Vite와 원활하게 작동합니다. 구성 요소 기반 아키텍처는 동적 단일 페이지 애플리케이션(SPA) 개발에 이상적입니다. Vite가 React 프로젝트에 탁월한 선택인 이유는 다음과 같습니다.

  • 즉시 서버 시작: 기존 번들러와 달리 Vite의 개발 서버는 파일을 기본 ES 모듈로 제공하여 개발 중에 번들링을 방지하여 거의 즉시 시작됩니다.

  • 빠른 핫 모듈 교체(HMR): Vite의 HMR은 놀라울 정도로 빠르므로 React 구성 요소의 변경 사항을 거의 즉시 확인할 수 있어 개발 속도가 빨라집니다.

  • 최적화된 프로덕션 빌드: 프로덕션의 경우 Vite는 롤업을 사용하여 번들을 최적화합니다. 여기에는 앱의 로드 시간을 향상시키는 자동 코드 분할과 같은 기능이 포함되어 있습니다.

  • 최신 개발 지원: Vite는 TypeScript, JSX와 같은 최신 JavaScript 도구, Sass와 같은 CSS 전처리기와 잘 작동하여 즉시 사용 가능한 최첨단 개발 경험을 제공합니다.

이 블로그에서는 Vite를 사용하여 React 프로젝트를 설정하는 방법을 안내하고, 프로젝트 구조를 살펴보고, 자산 작업 및 앱 배포 방법을 보여 드리겠습니다. 마지막에는 Vite가 어떻게 React 개발 경험을 향상시킬 수 있는지 알게 될 것입니다.

Vite 란 무엇입니까?

Vite는 특히 React와 같은 JavaScript 프레임워크로 작업할 때 속도와 효율성을 위해 설계된 최신 빌드 도구입니다. Vue.js의 창시자인 Evan You가 개발한 Vite는 빠르고 효율적인 개발 경험을 제공하는 능력으로 인해 두각을 나타냅니다.

VITE의 주요 기능

  1. 즉시 서버 시작: Vite는 기본 ES 모듈을 통해 파일을 제공하므로 대규모 프로젝트의 경우에도 개발 서버가 거의 즉시 시작될 수 있습니다.

  2. 빠른 핫 모듈 교체(HMR): Vite의 HMR은 매우 빠르므로 개발 중에 React 구성 요소를 거의 즉시 업데이트할 수 있습니다.

  3. 최적화된 빌드: Vite는 프로덕션 빌드에 롤업을 사용하여 코드 분할 및 트리 쉐이킹과 같은 기능으로 효율적인 번들링을 보장합니다.

  4. 최신 JavaScript 지원: Vite에는 TypeScript, JSX 및 Sass와 같은 CSS 전처리기를 포함한 최신 JavaScript 기능에 대한 지원이 내장되어 있습니다.

Vite 대 Webpack

Webpack은 수년간 인기 있는 선택이었지만 종종 복잡한 구성이 필요하고 번들링 프로세스로 인해 개발 중에 속도가 느려질 수 있습니다. 반면 Vite는 설정 프로세스를 단순화하고 개발 중에 번들링을 건너뛰므로 서버 시작 시간과 HMR이 더 빨라집니다. Vite의 프로덕션 빌드도 Webpack과 마찬가지로 고도로 최적화되어 있지만 구성이 더 간단합니다.

React와 함께 Vite를 사용하는 이유는 무엇입니까?

  1. 속도: Vite의 빠른 서버 시작과 HMR을 사용하면 오랜 번들링 프로세스를 기다리지 않고도 React 애플리케이션을 더 쉽게 개발할 수 있습니다.

  2. 단순성: Vite의 사용하기 쉬운 설정을 통해 빌드 도구를 구성하는 대신 React 구성요소를 구축하는 데 집중할 수 있습니다.

  3. 효율성: Vite는 React 앱이 빠르게 개발될 뿐만 아니라 최소한의 노력으로 제작에 최적화되도록 보장합니다.

Vite는 Webpack과 같은 기존 번들러에 대한 보다 현대적이고 효율적인 대안을 제공하므로 속도와 단순성을 우선시하는 React 프로젝트에 매우 적합합니다.

개발 환경 설정

React로 Vite를 시작하기 전에 시스템에 Node.js와 npm이 설치되어 있는지 확인해야 합니다. 설치되어 있지 않은 경우 아래 단계에 따라 시작하세요.

Node.js 및 npm 설치

Node.js와 npm을 설치하려면 Node.js 공식 웹사이트를 방문하여 최신 안정 버전을 다운로드하세요. 설치가 완료되면 터미널에서 다음 명령을 실행하여 설치를 확인할 수 있습니다.

node -v
npm -v
로그인 후 복사

이 명령은 설치된 Node.js 및 npm 버전을 표시하여 올바르게 설정되었는지 확인합니다.

새 Vite 프로젝트 초기화

Node.js와 npm이 준비되었으면 이제 Vite를 사용하여 새로운 React 프로젝트를 만들 수 있습니다. Vite는 새 프로젝트를 빠르게 설정할 수 있는 간단한 명령을 제공합니다. 터미널을 열고 다음 명령을 실행하세요.

npm create vite@latest my-react-app --template react
cd my-react-app
npm install
로그인 후 복사
  • npm create vite@latest my-react-app --template 반응: 이 명령은 React 템플릿을 사용하여 새 Vite 프로젝트를 초기화합니다. my-react-app을 원하는 프로젝트 이름으로 바꾸세요.
  • cd my-react-app: 새로 생성된 프로젝트 디렉토리로 이동합니다.
  • npm install: React 프로젝트에 필요한 종속성을 설치합니다.

개발 서버 실행

프로젝트가 설정되고 종속성이 설치되면 개발 서버를 시작할 수 있습니다. Vite의 서버는 빠르며 얼마나 빨리 시작되는지 확인할 수 있습니다:

npm run  dev
로그인 후 복사

이 명령을 실행하면 Vite 개발 서버가 시작되고 기본 웹 브라우저에서 새 React 애플리케이션이 열립니다. Vite의 빠른 HMR(핫 모듈 교체) 기능 덕분에 코드를 변경하면 애플리케이션이 자동으로 다시 로드됩니다.

이 명령을 실행하면 Vite 개발 서버가 시작되고 기본 웹 브라우저에서 새 React 애플리케이션이 열립니다. Vite의 빠른 HMR(핫 모듈 교체) 기능 덕분에 코드를 변경하면 애플리케이션이 자동으로 다시 로드됩니다.

프로젝트 구조 이해

Vite는 간단하고 체계적인 프로젝트 구조를 설정합니다. 주요 파일 및 폴더에 대한 간략한 개요는 다음과 같습니다.

  • index.html: 애플리케이션의 진입점입니다. Vite는 이 파일에 스크립트를 삽입합니다.
  • src/main.jsx: React 애플리케이션이 시작되는 기본 JavaScript 파일입니다. 일반적으로 루트 구성 요소(App.jsx)를 DOM으로 렌더링합니다.
  • src/App.jsx: 애플리케이션의 주요 React 구성 요소입니다. 여기에서 UI 구축을 시작할 수 있습니다.
  • vite.config.js: 빌드 프로세스를 사용자 정의하고 플러그인을 추가하는 등의 작업을 수행할 수 있는 Vite의 구성 파일입니다.

이 구조는 최소화하면서도 강력하게 설계되어 불필요한 복잡성 없이 React 애플리케이션 구축을 시작할 수 있는 견고한 기반을 제공합니다. 프로젝트가 성장함에 따라 구조를 쉽게 확장하고 사용자 정의할 수 있습니다.

프로젝트 구조 이해

Vite를 사용하여 React 프로젝트를 초기화하면 깔끔하고 최소한의 프로젝트 구조가 생성됩니다. 이 구조는 불필요한 파일이나 복잡한 구성으로 인한 오버헤드 없이 빠르게 시작할 수 있도록 설계되었습니다. 설정에 대한 이해를 돕기 위해 Vite에서 생성한 주요 파일과 폴더를 분석해 보겠습니다.

my-app
├── node_modules
├── src
├── .eslintrc.cjs
├── index.html
├── README.md
├── package.json
└── vite.config.js
로그인 후 복사

주요 파일 및 폴더 분석

  1. index.html: 이 파일은 애플리케이션의 진입점이며 루트 디렉터리에 있습니다. 기존 번들러와 달리 Vite는 개발 중에 이 HTML 파일을 직접 제공합니다. 여기에 React 애플리케이션이 마운트되고 Vite가 앱을 로드하는 데 필요한 스크립트를 삽입합니다.

  2. src/: src 폴더에는 모든 애플리케이션 코드가 포함됩니다.

  3. main.jsx: 이는 React 앱의 주요 진입점입니다. React를 가져와 루트 구성 요소(App.jsx)를 렌더링한 후 index.html 파일의 #root 요소에 연결합니다.

  4. App.jsx: 이는 UI 구축을 시작하는 애플리케이션의 루트 구성 요소입니다. 프로젝트가 성장함에 따라 이 파일을 수정하여 더 많은 구성 요소를 추가할 수 있습니다.

  5. vite.config.js: 이 파일에는 Vite의 구성이 포함되어 있습니다. 이를 통해 Vite의 동작을 사용자 정의하거나 플러그인을 추가하거나 빌드 프로세스를 수정할 수 있지만 대부분의 소규모 프로젝트에서는 이 파일을 건드릴 필요가 없을 수도 있습니다.

핵심 파일

  1. index.html : React 앱이 삽입되는 HTML 파일입니다. 여기에는 단일
    React 앱이 마운트될 id="root"인 요소입니다.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite React App</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>
로그인 후 복사
  1. src/main.jsx React 애플리케이션의 기본 JavaScript 진입점입니다. App 구성 요소를 index.html의 #root div로 렌더링합니다.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
로그인 후 복사
  1. src/App.jsx : React 앱의 주요 구성 요소입니다. 여기에서 UI 구축을 시작합니다. 기본적으로 여기에는 간단한 React 구성 요소가 포함되어 있지만 필요에 맞게 수정할 수 있습니다.
import React from 'react';

function App() {
  return (
    <div>
      <h1>Welcome to Vite + React!</h1>
    </div>
  );
}

export default App;
로그인 후 복사

App.jsx를 수정하여 간단한 React 구성 요소 만들기

기본 App.jsx 구성 요소를 수정하여 항목 목록을 표시하는 간단한 React 구성 요소를 만들어 보겠습니다.

import React from 'react';

function App() {
  const items = ['Item 1', 'Item 2', 'Item 3'];

  return (
    <div>
      <h1>Simple List with Vite and React</h1>
      <ul>
        {items.map((item, index) => (
          <li key={index}>{item}</li>
        ))}
      </ul>
    </div>
  );
}

export default App;
로그인 후 복사

이 예에서는:

  • We define an array items with a few sample items.
  • We use the map() function to iterate over the items array and render each item as a list item (
  • ).

This project structure offers flexibility and simplicity, allowing you to grow your application easily as you continue development.

Working with Vite in a React Project

Vite simplifies the process of working with assets, styles, and offers fast feedback during development through Hot Module Replacement (HMR). Let’s walk through how to handle these features in your Vite-React project.

Importing and Using Assets (Images, Styles)

Vite allows you to easily import assets such as images or CSS files directly into your React components, with the benefit of bundling them efficiently during the build.

import React from 'react';
import logo from './assets/logo.png'; // Importing an image

function App() {
  return (
    <div>
      <img src={logo} alt="App Logo" />
      <h1>Welcome to Vite React App!</h1>
    </div>
  );
}

export default App;
로그인 후 복사

In this example, Vite processes the logo.png image file and ensures it’s bundled efficiently when you build the project. During development, the image is served directly without bundling, contributing to faster reload times.

import React from 'react';
import './App.css'; // Importing a CSS file

function App() {
  return (
    <div className="app-container">
      <h1>Welcome to Vite React App!</h1>
    </div>
  );
}

export default App;
로그인 후 복사

How Vite Handles Hot Module Replacement (HMR)

One of Vite’s standout features is its fast Hot Module Replacement (HMR). HMR allows you to see changes in your application instantly without a full page reload. When you modify a file, Vite only updates the specific module that was changed, maintaining the application’s state.

For example, if you update a React component:

import React from 'react';

function App() {
  return (
    <div>
      <h1>Welcome to the updated Vite React App!</h1> {/* Change the text */}
    </div>
  );
}

export default App;
로그인 후 복사

Upon saving the file, Vite’s HMR immediately updates the UI without a full page reload. This speeds up the development process significantly, especially when you are working on UI components or tweaking styles.

Troubleshooting Common Issues

While Vite generally offers a smooth development experience, you might still run into a few common issues when using it with React. Here are some of those issues and how to fix them, along with tips for optimizing performance and build times.

  1. Error: "Failed to resolve module"

    This is a common issue that occurs when Vite cannot resolve a module you’re trying to import, especially when dealing with third-party libraries or incorrect paths.
    Solution:

  • Double-check the import paths in your code. Ensure you are importing the correct file or module.
  • For third-party libraries, try reinstalling the dependencies:
  npm install
로그인 후 복사
  • If the issue persists, clear Vite’s cache and restart the server

    rm -rf node_modules/.vite
    npm run dev
    
    로그인 후 복사
  1. Error: "React Refresh failed" Vite uses React Fast Refresh to enable Hot Module Replacement (HMR). Sometimes, this can fail, particularly when the React version is mismatched or there’s a configuration issue.

Solution:

  • Make sure that you're using a supported version of React (17.x or later).

  • Ensure that @vitejs/plugin-react is correctly installed and added to your vite.config.js file:

npm install @vitejs/plugin-react --save-dev
로그인 후 복사

In vite.config.js:

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

export default {
  plugins: [react()],
};
로그인 후 복사
  • Restart your Vite development server after applying these fixes.
  1. Assets Not Loading After

    If assets like images, fonts, or other static files are not loading properly after building the app, it’s often due to incorrect asset paths.

Solution:

  • Make sure that you're using relative paths for your assets. For example, use ./assets/logo.png instead of /assets/logo.png.
  • Check yourvite.config.js for the correct base path. If your app is deployed in a subdirectory, you may need to set the base option:

    export default {
    base: '/subdirectory/',
    };
    
    로그인 후 복사

Following these troubleshooting steps should help you resolve common issues and ensure your Vite + React project runs smoothly.

Conclusion

In this guide, we walked through setting up a React project with Vite, explored its project structure, imported assets, and styles, and highlighted how Vite's fast Hot Module Replacement (HMR) enhances development. You’ve also learned some common troubleshooting tips and optimizations for build performance.

Vite’s speed and simplicity make it a powerful tool, whether you’re working on small projects or scaling up to larger ones. As you continue to explore Vite, dive into its advanced features, such as plugins and environment-specific configurations, to make your development experience even better.

위 내용은 React와 함께 Vite를 사용하기 위한 초보자 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

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