The goal of this tutorial is to introduce you to the powerful combination of Vite and Preact. Vite is a modern and fast web development build tool, while Preact is a fast, 3kb alternative to React with the same modern API. You'll learn why these tools are used together and how they can enhance your web development process.
By the end of this tutorial, you will be able to:
Prerequisites:
To get started, you need to install Vite globally on your machine using the following npm command:
bash
npm install -g create-vite
With Vite installed, you can now create a new Vite-Preact project:
bash
create-vite my-vite-project --template preact
This command creates a new project in a folder called my-vite-project
with a template for Preact.
Your new project will have a structure similar to:
my-vite-project
├── index.html
├── package.json
├── src
│ ├── app.jsx
│ └── index.css
└── vite.config.js
The src
directory contains the main app file (app.jsx
) and the styles (index.css
). The vite.config.js
is where you can add Vite configuration options.
Navigate to your project's directory and start the Vite server:
bash
cd my-vite-project
npm run dev
This will start the development server at http://localhost:5000
.
To build your application for production, run:
bash
npm run build
This will create a dist
directory with the optimized version of your app.
Let's create a simple Preact component:
// src/App.jsx
import { h } from 'preact';
function App() {
return (
<div>
<h1>Hello, Vite and Preact!</h1>
</div>
);
}
export default App;
In this snippet, we create a functional component App
that returns a simple JSX markup displaying a message. We then export this component to be used in our application.
In this tutorial, you learned about the powerful combination of Vite and Preact, how to create a new project using these tools, and how to run and build your application.
To continue learning, explore more about Vite's features such as its Hot Module Replacement and Preact's features like hooks and context API.
Additional resources:
Solution:
jsx
function Welcome({ name }) {
return <h1>Welcome, {name}!</h1>;
}
Explanation: This component accepts a name
prop and uses it to display a personalized welcome message.
index.css
.Solution:
```jsx
// index.css
.welcome {
color: blue;
font-size: 2em;
}
// App.jsx
function Welcome({ name }) {
return
Explanation: We first define our styles in index.css
. Then, we apply the welcome
class to our Welcome
component using the className
attribute.
Solution: When you run npm run dev
, Vite automatically enables Hot Module Replacement. Just save your changes and see them instantly reflected in your browser.
Explanation: Vite's Hot Module Replacement (HMR) allows you to see your changes in real-time without a full page refresh, improving your development experience.