講了六篇 Sanity 設定,也是時候把前端專案啟動起來了。
使用 create-next-app
啟動一個空的 Next.js 專案:
npx create-next-app@latest
我的設定是這樣:
( 依照自己習慣建立就好了 )
npx create-next-app@latest
✔ What is your project named? … next-app
✔ Would you like to use TypeScript? … Yes
✔ Would you like to use ESLint? … Yes
✔ Would you like to use Tailwind CSS? … Yes
✔ Would you like to use `src/` directory? … No
✔ Would you like to use App Router? (recommended) … Yes
✔ Would you like to customize the default import alias (@/*)? … No
完成後只要到專案目錄內執行 npm run dev
可以成功就好了。
接著就可以開始設定 Next.js 專案與 Sanity 的連線了。
首先創建一個 .env.local
檔案,並且在裡面寫下 project id 跟 dataset:
NEXT_PUBLIC_SANITY_PROJECT_ID=zxxxxxxg
NEXT_PUBLIC_SANITY_DATASET=production
接著創建一個檔案把設定把變數 export 出去 ./app/sanity/env.ts
export const projectId = process.env.NEXT_PUBLIC_SANITY_PROJECT_ID!;
export const dataset = process.env.NEXT_PUBLIC_SANITY_DATASET!;
再來透過 npm 安裝 next-sanity
最後創建 ./app/sanity/lib/client.ts
連線的設定檔
import { createClient } from "next-sanity";
import { dataset, projectId } from "../env";
export const client = createClient({
projectId,
dataset,
useCdn: true,
});
到這邊,連線的設定基本就完成了。
前幾篇在 Sanity 中建立了一個叫 blogPost
的 schema,現在來試著把文章清單拿出來吧!
先建立一個 queries file./app/sanity/lib/queries.ts
import { defineQuery } from "next-sanity";
export const BLOG_POSTS_QUERY = defineQuery(`*[_type == "blogPost"]`);
在 ./app/page.tsx
引入並渲染在畫面:
import { client } from "@/app/sanity/lib/client";
import { BLOG_POSTS_QUERY } from "@/app/sanity/lib/queries";
export default async function Home() {
const posts = await client.fetch(BLOG_POSTS_QUERY);
console.log(posts);
return (
<ul className="home-page">
{posts.map((post) => (
<li key={post._id}>
<a href={`/posts/${post?.slug}`}>{post?.title}</a>
</li>
))}
</ul>
);
}
這樣就完成了!
現在還會有一些型別錯誤或各種技術細節,等下一篇再來介紹更進階的設定。