用途
本技能用于从零开始引导创建一个全新的 Encore.ts 项目。它仅面向首次安装 Encore CLI 以及使用 encore app create 创建应用的场景,不适用于架构设计或功能相关问题。
主要能力
- 提供各平台安装 Encore CLI 的命令。
- 提供创建新应用的方式(交互式选择模板,或使用空白示例)。
- 说明最小 Encore.ts 应用的项目结构。
- 给出 encore.app 配置文件、服务定义文件、首个 API 端点的示例代码。
- 说明如何运行应用、打开本地开发仪表盘。
- 列出常用 CLI 命令。
- 说明如何添加数据库与创建迁移文件。
使用方式
安装 Encore CLI
macOS:
brew install encoredev/tap/encore
Linux/WSL:
curl -L https://encore.dev/install.sh | bash
Windows (PowerShell):
iwr https://encore.dev/install.ps1 | iex
创建新应用
交互式选择模板:
encore app create my-app
或从空白应用开始:
encore app create my-app --example=ts/hello-world
项目结构
一个最小的 Encore.ts 应用:
my-app/
├── encore.app # App configuration
├── package.json # Dependencies
├── tsconfig.json # TypeScript config
├── encore.service.ts # Service definition
└── api.ts # API endpoints
encore.app 文件
// encore.app
{
"id": "my-app"
}
该文件标记 Encore 应用的根目录,id 是应用的唯一标识符。
定义服务
创建 encore.service.ts 来定义服务:
// encore.service.ts
import { Service } from "encore.dev/service";
export default new Service("my-service");
创建第一个 API
// api.ts
import { api } from "encore.dev/api";
interface HelloResponse {
message: string;
}
export const hello = api(
{ method: "GET", path: "/hello", expose: true },
async (): Promise<HelloResponse> => {
return { message: "Hello, World!" };
}
);
运行应用
启动开发服务器:
encore run
API 随后可在 http://localhost:4000 访问。
打开本地仪表盘
encore run
# Then visit http://localhost:9400
仪表盘展示:
- 所有服务与端点
- 请求/响应日志
- 数据库查询
- 追踪与跨度(traces and spans)
常用 CLI 命令
| 命令 | 描述 |
|---|---|
encore run |
启动本地开发服务器 |
encore test |
运行测试 |
encore db shell <db> |
打开数据库的 psql shell |
encore gen client |
生成 API 客户端代码 |
encore app link |
链接到已有的 Encore Cloud 应用 |
添加数据库
// db.ts
import { SQLDatabase } from "encore.dev/storage/sqldb";
const db = new SQLDatabase("mydb", {
migrations: "./migrations",
});
创建迁移:
-- migrations/1_create_table.up.sql
CREATE TABLE items (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL
);
后续步骤
- 添加更多端点(参见 encore-api 技能)
- 添加认证(参见 encore-auth 技能)
- 添加 Pub/Sub 主题(encore-pubsub)、cron 任务(encore-cron)、存储桶(encore-bucket)、密钥(encore-secret)或缓存(encore-cache)
- 部署到 Encore Cloud:先
encore app link,然后git push encore
适用场景
适用于首次安装 Encore CLI、创建全新 Encore.ts 项目、了解最小项目结构与基础 API 编写方式的开发者。
限制
本技能仅覆盖首次 CLI 安装与 encore app create 创建应用的流程,不适用于架构或功能相关问题。