安装与项目创建
本页介绍如何安装 Vitarx 并创建你的第一个项目。
使用脚手架创建项目
Vitarx 提供了官方脚手架工具 create-vitarx,可以快速创建一个开箱即用的项目。
bash [npm]
npm create vitarx@latestbash [pnpm]
pnpm create vitarx@latestbash [yarn]
yarn create vitarx@latest运行后按照提示依次选择:
- 项目名称 — 输入你的项目目录名
- 开发语言 — 选择 TypeScript 或 JavaScript
- 项目模板 — 选择适合的模板
脚手架会自动生成项目结构并安装依赖,默认模板包含以下特性:
- 基于 Vite 的开发环境
- Vitarx 核心框架
- Vitarx Router 路由支持
- 代码格式化配置
- 开发服务器热重载
提示
使用脚手架需要 Node.js >= 18.0.0。
使用包管理器安装
Vitarx 已发布到 npm,你可以使用任意包管理器安装:
bash [npm]
npm install vitarxbash [pnpm]
pnpm add vitarxbash [yarn]
yarn add vitarx手动创建项目
Vitarx 基于 Vite 构建,下面我们从零搭建一个最小项目。
1. 创建项目目录
bash
mkdir my-vitarx-app && cd my-vitarx-app
npm init -y2. 安装依赖
bash
npm install vitarx
npm install -D vite typescript @vitarx/plugin-vite3. 创建 HTML 入口
创建 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>My Vitarx App</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>4. 创建应用入口
创建 src/main.tsx:
tsx
import { createApp } from 'vitarx'
function App() {
return <div>Hello, Vitarx!</div>
}
createApp(App).mount('#app')5. 配置 Vite
创建 vite.config.ts:
ts
import { defineConfig } from 'vite'
import vitarx from '@vitarx/plugin-vite'
export default defineConfig({
plugins: [vitarx()]
})6. 配置 TypeScript
创建 tsconfig.json:
json
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "preserve",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"outDir": "dist"
},
"include": ["src"]
}提示
jsx 必须设置为 "preserve",因为 Vitarx 的编译由 @vitarx/plugin-vite 在 Vite 构建阶段完成,不需要 TypeScript 额外处理 JSX。
7. 添加启动脚本
在 package.json 中添加:
json
{
"scripts": {
"dev": "vite",
"build": "vite build",
"preview": "vite preview"
}
}8. 启动开发服务器
bash
npm run dev打开浏览器访问 Vite 输出的地址,你就能看到页面上的 “Hello, Vitarx!” 了。
最小项目结构
完成以上步骤后,你的项目结构如下:
text
my-vitarx-app/
├── index.html
├── package.json
├── tsconfig.json
├── vite.config.ts
└── src/
└── main.tsx这就是运行 Vitarx 所需的最少文件。随着项目增长,你可以按需添加更多文件和目录。
下一步
- 创建应用 — 了解
createApp的完整用法