Preact安装 #
一、环境准备 #
1.1 前置要求 #
| 要求 | 版本 | 说明 |
|---|---|---|
| Node.js | >= 16.0 | 推荐使用 LTS 版本 |
| npm/yarn/pnpm | 最新版 | 包管理器 |
| 编辑器 | VS Code | 推荐安装 Preact 插件 |
1.2 检查环境 #
bash
# 检查 Node.js 版本
node -v
# 检查 npm 版本
npm -v
# 检查 pnpm 版本(如已安装)
pnpm -v
二、使用 Vite 创建项目(推荐) #
2.1 创建新项目 #
bash
# 使用 npm
npm create vite@latest my-preact-app -- --template preact
# 使用 yarn
yarn create vite my-preact-app --template preact
# 使用 pnpm
pnpm create vite my-preact-app --template preact
2.2 项目结构 #
text
my-preact-app/
├── node_modules/
├── public/
│ └── vite.svg
├── src/
│ ├── assets/
│ ├── app.css
│ ├── app.jsx
│ ├── index.css
│ └── main.jsx
├── .gitignore
├── index.html
├── package.json
└── vite.config.js
2.3 启动开发服务器 #
bash
cd my-preact-app
# 安装依赖
npm install
# 启动开发服务器
npm run dev
2.4 vite.config.js 配置 #
javascript
import { defineConfig } from 'vite';
import preact from '@preact/preset-vite';
export default defineConfig({
plugins: [preact()],
server: {
port: 3000,
open: true
},
build: {
outDir: 'dist'
}
});
三、使用 Preact CLI #
3.1 安装 Preact CLI #
bash
npm install -g preact-cli
3.2 创建项目 #
bash
# 使用默认模板
preact create default my-app
# 使用 TypeScript 模板
preact create typescript my-app
# 使用自定义模板
preact create my-template my-app
3.3 项目结构 #
text
my-app/
├── build/
├── node_modules/
├── src/
│ ├── components/
│ │ ├── app.js
│ │ └── header.js
│ ├── routes/
│ │ ├── home/
│ │ └── profile/
│ ├── index.js
│ └── manifest.json
├── package.json
└── preact.config.js
3.4 常用命令 #
bash
# 启动开发服务器
preact watch
# 构建生产版本
preact build
# 预览生产构建
preact serve
# 检查构建大小
preact build --analyze
四、手动配置项目 #
4.1 创建项目目录 #
bash
mkdir my-preact-app
cd my-preact-app
npm init -y
4.2 安装依赖 #
bash
# 安装 Preact
npm install preact
# 安装开发依赖
npm install -D vite @preact/preset-vite
# 安装 TypeScript(可选)
npm install -D typescript @types/node
4.3 创建文件结构 #
bash
mkdir src public
touch index.html src/main.jsx src/app.jsx
4.4 配置文件 #
index.html
html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Preact App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
src/main.jsx
jsx
import { render } from 'preact';
import { App } from './app';
import './index.css';
render(<App />, document.getElementById('app'));
src/app.jsx
jsx
import { useState } from 'preact/hooks';
export function App() {
const [count, setCount] = useState(0);
return (
<div>
<h1>Hello Preact!</h1>
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
</div>
);
}
4.5 package.json 脚本 #
json
{
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
}
}
五、TypeScript 配置 #
5.1 安装 TypeScript #
bash
npm install -D typescript @types/node
5.2 tsconfig.json #
json
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"jsxImportSource": "preact",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
5.3 TypeScript 组件示例 #
tsx
import { useState } from 'preact/hooks';
interface AppProps {
title: string;
}
export function App({ title }: AppProps) {
const [count, setCount] = useState<number>(0);
return (
<div>
<h1>{title}</h1>
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
</div>
);
}
六、添加 React 兼容层 #
6.1 安装 preact/compat #
bash
npm install preact
6.2 配置别名(Vite) #
javascript
import { defineConfig } from 'vite';
import preact from '@preact/preset-vite';
export default defineConfig({
plugins: [preact()],
resolve: {
alias: {
'react': 'preact/compat',
'react-dom': 'preact/compat'
}
}
});
6.3 使用 React 生态库 #
jsx
import { render } from 'preact';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
const store = configureStore({ reducer: rootReducer });
function App() {
return (
<Provider store={store}>
<Main />
</Provider>
);
}
七、开发工具配置 #
7.1 VS Code 配置 #
.vscode/settings.json
json
{
"editor.formatOnSave": true,
"editor.defaultFormatter": "esbenp.prettier-vscode",
"emmet.includeLanguages": {
"javascript": "javascriptreact"
}
}
7.2 ESLint 配置 #
bash
npm install -D eslint @preact/eslint-config
.eslintrc.json
json
{
"extends": ["@preact"]
}
7.3 Prettier 配置 #
bash
npm install -D prettier
.prettierrc
json
{
"singleQuote": true,
"trailingComma": "none",
"jsxSingleQuote": false,
"semi": true
}
八、常见问题 #
8.1 JSX 不识别 #
javascript
// vite.config.js
import { defineConfig } from 'vite';
import preact from '@preact/preset-vite';
export default defineConfig({
plugins: [preact()]
});
8.2 热更新不工作 #
javascript
// vite.config.js
export default defineConfig({
server: {
hmr: true
}
});
8.3 生产构建优化 #
javascript
// vite.config.js
export default defineConfig({
build: {
minify: 'terser',
terserOptions: {
compress: {
drop_console: true
}
}
}
});
九、总结 #
| 方式 | 适用场景 | 优点 |
|---|---|---|
| Vite | 新项目、快速开发 | 极快的冷启动 |
| Preact CLI | 完整项目、SSR | 内置最佳实践 |
| 手动配置 | 学习、定制需求 | 完全控制 |
推荐选择:
- 新项目:使用 Vite + Preact 模板
- 企业项目:使用 Preact CLI
- 学习研究:手动配置
最后更新:2026-03-28