Skip to content

Netlify

Netlify 提供静态网站托管和无服务器后端服务。Edge Functions 使我们能够使网页动态化。

🌐 Netlify provides static site hosting and serverless backend services. Edge Functions enables us to make the web pages dynamic.

Edge Functions 支持使用 Deno 和 TypeScript 编写,并且可以通过 Netlify CLI 轻松部署。使用 Hono,你可以为 Netlify Edge Functions 创建应用。

🌐 Edge Functions support writing in Deno and TypeScript, and deployment is made easy through the Netlify CLI. With Hono, you can create the application for Netlify Edge Functions.

1. 设置

🌐 1. Setup

Netlify 的入门模板已可用。使用 "create-hono" 命令启动你的项目。此示例请选择 netlify 模板。

🌐 A starter for Netlify is available. Start your project with "create-hono" command. Select netlify template for this example.

sh
npm create hono@latest my-app
sh
yarn create hono my-app
sh
pnpm create hono my-app
sh
bun create hono@latest my-app
sh
deno init --npm hono my-app

移动到 my-app

🌐 Move into my-app.

2. 你好,世界

🌐 2. Hello World

编辑 netlify/edge-functions/index.ts

🌐 Edit netlify/edge-functions/index.ts:

ts
import { Hono } from 'jsr:@hono/hono'
import { handle } from 'jsr:@hono/hono/netlify'

const app = new Hono()

app.get('/', (c) => {
  return c.text('Hello Hono!')
})

export default handle(app)

3. 跑

🌐 3. Run

使用 Netlify CLI 运行开发服务器。然后,在你的网页浏览器中访问 http://localhost:8888

🌐 Run the development server with Netlify CLI. Then, access http://localhost:8888 in your Web browser.

sh
netlify dev

4. 部署

🌐 4. Deploy

你可以使用 netlify deploy 命令进行部署。

🌐 You can deploy with a netlify deploy command.

sh
netlify deploy --prod

Context

你可以通过 c.env 访问 Netlify 的 Context

🌐 You can access the Netlify's Context through c.env:

ts
import { Hono } from 'jsr:@hono/hono'
import { handle } from 'jsr:@hono/hono/netlify'

// Import the type definition
import type { Context } from 'https://edge.netlify.com/'

export type Env = {
  Bindings: {
    context: Context
  }
}

const app = new Hono<Env>()

app.get('/country', (c) =>
  c.json({
    'You are in': c.env.context.geo.country?.name,
  })
)

export default handle(app)

Hono 中文网 - 粤ICP备13048890号