在 JavaScript 前端世界中,不断有新的工具来构建和优化项目。 React 是一种用于构建用户界面的流行 JavaScript 库,传统上与 Create-React-App (CRA) 配合使用以简化设置和开发。然而,一种名为 Vite 的新工具因其速度和效率而迅速获得关注,为 CRA 提供了现代替代品。
在这篇博文中,我们将首先介绍使 Vite 成为 React 开发人员的绝佳选择的具体功能,然后我们将仔细研究 Create-React-App。之后,我们将比较这两种工具,帮助您决定何时使用每种工具以及何时从 CRA 切换到 Vite。
无论您是开始一个新的 React 项目还是考虑迁移现有项目,我们都会指导您完成整个过程,帮助您选择最适合您需求的工具。此外,我们将为那些想要充分利用 Vite 和 React 设置的人探索高级配置和优化技术。
读完本文,您将获得以下关键问题的答案:
Vite 有哪些独特功能使其成为 React 开发的绝佳选择?
Create-React-App 与 Vite 在性能、配置和灵活性方面相比如何?
什么时候应该坚持使用 Create-React-App,什么时候改用 Vite 更好?
使用 Vite 建立一个新的 React 项目需要哪些步骤?
如何将现有的 Create-React-App 项目迁移到 Vite?
您可以应用哪些高级配置和优化技术来充分利用 Vite 和 React 设置?
Vite 是一款旨在让 Web 开发更快、更高效的构建工具。 “Vite”这个名字来自法语单词“快”。 Vite 由 Vue.js 的开发者 Evan You 创建,旨在解决 Webpack 等传统捆绑器的性能限制。
它提供对 React、Vue 和 Svelte 等流行框架的支持。其灵活性使其能够兼容多种前端技术,确保能够适应各种开发需求。它利用本机 ECMAScript 模块和现代浏览器功能来提供快速开发环境。
无论您是构建简单的 React 应用程序还是复杂的 Web 应用程序,Vite 都能提供简化的体验,从而节省您的时间。
像 Webpack 这样的传统构建工具已经存在多年,并且为开发者社区提供了良好的服务。然而,随着 Web 应用程序变得越来越复杂,启动开发服务器并查看浏览器中反映的更改所需的时间也越来越长。
下图描述了传统的捆绑方法。该过程从连接到应用程序的各种路由和模块的入口点开始。在服务器准备好使用之前,所有这些组件都捆绑在一起。这种预先捆绑非常耗时,尤其是随着应用程序的增长,导致开发服务器的启动时间更长。
Vite 在开发过程中采用不同的方法来构建和服务您的应用程序。服务器几乎立即准备就绪,而不是预先捆绑所有内容,并且浏览器仅在需要时请求所需的特定模块。这是通过原生 ES 模块 (ESM) 支持实现的,它允许动态导入、实现代码分割并减少在任何给定时间需要处理的代码量。通过只提供必要的服务,Vite 确保了更快的反馈循环,让开发者能够更高效地工作。
以下是Vite的核心功能:
即时服务器启动:
使用传统工具,启动开发服务器可能需要一段时间,尤其是对于大型项目。然而,Vite 几乎立即启动。它仅通过转换您当前正在处理的代码而不是整个项目来实现此目的。这使您的开发体验更加顺畅且响应更快。
Lightning-Fast Hot Module Replacement (HMR):
Hot Module Replacement (HMR) allows you to see the results of your code changes in real-time, without needing to refresh the browser. Vite’s HMR is incredibly fast because it updates only the specific modules that were changed, not the entire application. This instant feedback loop makes for a much more efficient development process.
Support for Native ES Modules:
Vite leverages the native ES module support that’s built into modern browsers. Instead of bundling your entire codebase into a few large files (as with traditional tools), Vite serves each module as a separate file. This reduces the need for complex transformations and speeds up both the initial load and subsequent updates.
Optimized Build Process using Rollup:
Vite is also powerful in production. When you’re ready to deploy, Vite bundles your code efficiently using Rollup, a modern module bundler. This means you get the best of both worlds: fast development and optimized production builds.
Flexible Configuration in vite.config.js:
Vite is highly customizable. With a straightforward configuration file (vite.config.js), you can easily tweak settings to match your project’s needs. Whether you need to set up environment variables, configure path aliases, or add plugins, Vite makes it simple.
Native TypeScript Support:
Both React and Vite natively support TypeScript, making it easy to incorporate static typing into your code. Using TypeScript helps catch errors earlier in the development process and enhances code maintainability.
Create-React-App (CRA) is a popular tool developed by Facebook that simplifies the process of setting up a new React project. It allows developers to quickly start building React applications without the need to manually configure a development environment.
Before CRA, setting up a React project required configuring a variety of tools, which could be a daunting task, especially for those new to React. To address this challenge, CRA was introduced in 2016 as a solution that provides a zero-configuration setup. This tool enabled developers to jump straight into writing React code without worrying about the complexities of build tools and configurations.
CRA quickly became the standard tool for React developers because it streamlined project setup and brought consistency to development environments, making it easier for teams to collaborate effectively.
These are the core features of CRA:
Dependency Tree Creation with Webpack:
CRA uses Webpack to analyze your project’s index.js file, which acts as the entry point for your application. Webpack then creates a tree of dependencies by linking together all the modules your project needs. This automated process ensures that your application has all the necessary resources bundled together.
Code Transpilation with Babel:
Once the dependency tree is built, CRA employs Babel to transpile your modern JavaScript into a version that is compatible with a wider range of browsers. This step ensures that your app can run smoothly across different environments, regardless of whether they support the latest JavaScript features.
Code Bundling and Serving:
After transpilation, Webpack bundles your application’s code into a few compressed files. These bundles are then served through a web server, making your app accessible via a local development server.
No Configuration Required:
One of the biggest advantages of CRA is that it provides a fully functional React setup. When you create a new project with CRA, it automatically sets up everything you need like Webpack for bundling, Babel for transpiling modern JavaScript, and ESLint for linting. This means you can start coding immediately without spending time configuring your environment.
In this section, we’ll compare Vite and CRA across several key areas which configuration, performance, support, and features to help you determine when it might make sense to switch from CRA to Vite.
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 |
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é.
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.
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.
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.
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.
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/
And that’s it! You’ve successfully set up a new React project using 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.
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
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.
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.
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()], });
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';
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 }
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) },
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.
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.
The above is the detailed content of Tutorial: How to Create a React App with Vite. For more information, please follow other related articles on the PHP Chinese website!