新聞中心
審校 | 孫淑娟 梁策

網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)!專注于網(wǎng)頁設(shè)計(jì)、網(wǎng)站建設(shè)、微信開發(fā)、小程序定制開發(fā)、集團(tuán)企業(yè)網(wǎng)站建設(shè)等服務(wù)項(xiàng)目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了鞏義免費(fèi)建站歡迎大家使用!
使用工具
??Next.js??- 用于生產(chǎn)的 React 框架,可以輕松地啟動全棧應(yīng)用程序。
??Cosmic?? - 無頭部 CMS工具,它實(shí)現(xiàn)了數(shù)據(jù)(內(nèi)容)層的獨(dú)立性,并使我們能夠快速管理網(wǎng)站內(nèi)容。
??Sass ??- 一種穩(wěn)定、強(qiáng)大的專業(yè)級 CSS 擴(kuò)展語言。
相關(guān)資源
- ??代碼??
- ??現(xiàn)場演示??
- ??安裝應(yīng)用模板??
相關(guān)工具介紹
Next.js是一個完整的套件,用于構(gòu)建超快的 React 應(yīng)用程序。它對開發(fā)人員友好,使用輕松。隨著??Next.js 12.1??的發(fā)布,性能優(yōu)化、中間件、React 18 支持、按需 ISR、對 SWC 的擴(kuò)展支持等新功能只會變得更好。
Cosmic是一款出色的無頭 CMS,它使我們能夠全面管理和存儲網(wǎng)站內(nèi)容和媒體,并進(jìn)行快速更新。
探索 Next.js 的 4 個新殺手級功能并將其用于模板
先安裝一個新的包含工具和配置的?? Next.js應(yīng)用程序???。本教程中使用??Node.js ??12.22.0 或更高版本。
打開終端,輸入:
npx create-next-app@latest nextjs-restaurant-website-cms
# or
yarn create next-app nextjs-restaurant-website-cms
安裝依賴
cd nextjs-restaurant-website-cms
npm i
# or
cd nextjs-restaurant-website-cms
yarn
開始運(yùn)行
npm run dev
# or
yarn dev
在瀏覽器中打開 ??*http://localhost:3000/*以查看主頁??。
1. Rust 編譯器
Next.js 12 的關(guān)鍵特性之一是性能優(yōu)化。為了提高性能,Next.js 用可擴(kuò)展的 Rust 編譯器替換了 Babel 編譯器,并默認(rèn)使用 Next.js 12 啟用它,該??編譯器構(gòu)建???在??SWC??(Speedy Web Compiler)之上,它支持SWC。它可以將TypeScript和JavaScript轉(zhuǎn)化為可以在舊瀏覽器上運(yùn)行的 JavaScript 代碼。
SWC 在單線程上比 Babel 快 20 倍,在四核上快 70 倍。
2. 中間件
這是最令人興奮的功能之一。中間件使我們能夠使用代碼而不是配置。這意味著你可以在請求完成之前運(yùn)行代碼,并根據(jù)請求,你可以通過重寫、重定向、添加標(biāo)頭、設(shè)置 Cookie 等來修改響應(yīng)。通過中間件,你可以實(shí)現(xiàn)??身份驗(yàn)證、機(jī)器人保護(hù)、重定向、重寫、服務(wù)器端分析、日志記錄和處理不受支持的瀏覽器??等。
中間件被創(chuàng)建在 /pages/_middleware.ts ,它將在/pages目錄中的所有路由上運(yùn)行。_middleware.js文件長什么樣?讓我們以我們的模板為例。
// pages/_middleware.js
import { NextResponse } from 'next/server';
export async function middleware( request ) {
// create an instance of the class to access the public methods.
//This uses next(),
let response = NextResponse.next();
const country = request.geo.country || 'US';
const city = request.geo.city || 'San Francisco';
const region = request.geo.region || 'CA';
// get the cookies from the request
let cookieFromRequest = request.cookies['location-cookie'];
if(!cookieFromRequest) {
// set the `cookie`
response.cookie('location-cookie', `${country|city|region}`);
}
return response;
}
3.按需增量靜態(tài)再生??ISR??
Next.js 公開了一個函數(shù)unstable_revalidate(),允許你使用getStaticProps重新授權(quán)各個頁面。在getStaticProps中,你不需要指定 revalidate 來按需重新驗(yàn)證,只需要在unstable_revalidate()調(diào)用時按需重新驗(yàn)證頁面。
// pages/api/revalidate.js
export default async function handler(req, res) {
try {
await res.unstable_revalidate('/menu/' + req.body.data.slug)
return res.json({ revalidated: true })
} catch (err) {
// If there was an error, Next.js will continue
// to show the last successfully generated page
return res.status(500).send('Error revalidating')
}
}
4. 使用 AVIF 實(shí)現(xiàn)更快的圖像優(yōu)化和更小的圖像
內(nèi)置的圖像優(yōu)化API已更新以支持與ISR頁面相同的模式,即在后臺提供過時的圖像并重新驗(yàn)證。此外,它還支持 AVIF 圖像,使圖像比 WebP 小 20%。
此功能是可選的,在編輯圖片配置的時候可以選擇啟用。在文件next.config.js中配置下面參數(shù)即可:
// next.config.js
const nextConfig = {
reactStrictMode: true,
images: {
formats: ['image/avif', 'image/webp'],
domains: ['imgix.cosmicjs.com'],
},
}
module.exports = nextConfig
Cosmic 特征概述
- 可定制的 API:用戶自己定義 API 的 schema,models和 controllers。為方便起見, Cosmic 同時提供了REST 和 GraphQL API的方式。
- 快速且安全的內(nèi)容管理系統(tǒng)和 API 工具包。
- Webhooks在你需要的任何地方回調(diào),以獲得你想要的功能,使用 Cosmic API 開箱即用。
- ??包含Imgix??集成,可讓你為針對跨平臺體驗(yàn)優(yōu)化的動態(tài)應(yīng)用程序進(jìn)行強(qiáng)大的圖像處理。
Cosmic 操作
第一步創(chuàng)建??免費(fèi)的 Cosmic 帳戶??。讓我們選擇“從頭開始”(Start from scratch)選項(xiàng)。
現(xiàn)在讓我們將內(nèi)容放進(jìn)groups,用Object Type來共享組里的內(nèi)容。例如,部分名稱、標(biāo)題、簡介和圖片等具有類似屬性的部分,這些模塊希望得到復(fù)用以為不同部分創(chuàng)建內(nèi)容。
創(chuàng)建Object Type并添加部分屬性用來在“Content Model”中定義“Metafields”。
現(xiàn)在,你可以為部分創(chuàng)建一個Object Type模型,并且可以像這樣填充內(nèi)容。
以類似的方式,你可以按照當(dāng)前的數(shù)據(jù)模型、架構(gòu)設(shè)計(jì)定義模塊并創(chuàng)建Object Type:
- Singleton 為一個單獨(dú)的模型
- Multiple 為可重復(fù)使用的模型
是時候獲取 Next.js 應(yīng)用程序的值了
將 Cosmic 模塊安裝到 Next.js 應(yīng)用程序中。
npm i cosmicjs
# or
yarn add cosmicjs
然后,轉(zhuǎn)到 Cosmic 面板 Your Bucket > Settings > API Access并找到你的 Bucket slug 和 API 讀取密鑰。
將此 Bucket slug 和 API 讀取密鑰添加到你的 Next.js 應(yīng)用程序.env中。
//.env
COSMIC_BUCKET_SLUG=your_cosmic_slug
COSMIC_READ_KEY=your_cosmic_read_key
要使用模板 UI,你需要在??GitHub??中將它克隆。打開終端,粘貼或鍵入此代碼以安裝所有依賴項(xiàng),然后運(yùn)行它。
git clone https://github.com/cosmicjs/nextjs-restaurant-website-cms.git
cd nextjs-restaurant-website-cms
npm install
#or
yarn install
npm run dev
#or
yarn dev
向我們之前在 Cosmic 面板中創(chuàng)建的函數(shù)getDataFromBucket請求,并按類型從 Cosmic 中獲取我們創(chuàng)建的內(nèi)容params。
// src/lib/api.js
import Cosmic from 'cosmicjs';
const BUCKET_SLUG = process.env.COSMIC_BUCKET_SLUG
const READ_KEY = process.env.COSMIC_READ_KEY
const bucket = Cosmic().bucket({
slug: BUCKET_SLUG,
read_key: READ_KEY,
});
export async function getDataFromBucket(preview) {
const params = {
type: 'header',
props: 'title,slug,metadata,created_at',
sort: '-created_at',
...(preview && { status: 'all' }),
}
const data = await bucket.getObjects(params)
return data.objects
}
顯示我們的內(nèi)容,將其與我們的 UI 集成,并將一些元素呈現(xiàn)到主頁。為此,你需要將此添加到index.js。
// pages/index.js
import Head from 'next/head';
import Home from 'components/Home';
import Layout from 'components/Layout';
import Footer from 'components/Footer';
import AboutUs from 'components/AboutUs';
import SpacialMenu from 'components/Menu';
import Introduction from 'components/Introduction';
import VideoIntro from 'components/VideoIntro';
import Gallery from 'components/Gallery';
import Contacts from 'components/Contact';
import { getDataFromBucket } from 'lib/api';
import chooseByType from 'utils/chooseValueByType';
function Template({ data }) {
return (
<>
Next.js Restaurant CMS
>
)
}
export async function getStaticProps({ preview }) {
const data = (await getDataFromBucket(preview)) || [];
return {
props: { data },
}
}
export default Template;
下面函數(shù)chooseByType將過濾我們在 Cosmic 面板中創(chuàng)建的 Object Type。(Slug)
(Slug)
// src/utils/chooseValueByType.js
const chooseByType = (data, slugName) => {
if( data && slugName ) {
const chooseBySlug = data?.filter(content => Object.values(content).includes(slugName));
return chooseBySlug ? chooseBySlug[0] : [];
}
}
export default chooseByType;
制作菜單項(xiàng)頁面
在 Next.js 中,你可以創(chuàng)建動態(tài)路由,可以考慮用下面pages/menu/[slug].js頁面來創(chuàng)建單個菜單項(xiàng)頁面和動態(tài)路由:
// pages/menu/[slug].js
import Head from 'next/head';
import { useRouter } from 'next/router';
import Layout from 'components/Layout';
import Footer from 'components/Footer';
import Contacts from 'components/Contact';
import MenuIntro from 'components/MenuIntro';
import VideoIntro from 'components/VideoIntro';
import Gallery from 'components/Gallery';
import { getAllDataWithSlug,getDataFromBucket } from 'lib/api';
import chooseByType from 'utils/chooseValueByType';
function Menu({ data }) {
const {
query: {slug},
} = useRouter();
return (
<>
Next.js Restaurant CMS
>
)
}
export async function getStaticProps({ params, preview = null }) {
const data = (await getDataFromBucket(preview)) || [];
return {
props: { data },
}
}
export async function getStaticPaths() {
const dataWithSlug = (await getAllDataWithSlug()) || [];
return {
paths: dataWithSlug.map((menu) => `/menu/${menu.slug}`),
fallback: true,
}
}
export default Menu;
該函數(shù)getServerSideProps用于每次調(diào)用此路由時從 Cosmic 獲取數(shù)據(jù)。在pages/api/revalidate.js中,我們在unstable_revalidate()被調(diào)用時使用unstable_revalidate函數(shù)來按需重新驗(yàn)證頁面。如果出現(xiàn)錯誤,Next.js 將繼續(xù)顯示最后成功生成的頁面。
在??Vercel??上部署代碼庫后,你可以通過轉(zhuǎn)到 Cosmic 面板并導(dǎo)航到Bucket Settings > Webhooks來啟用內(nèi)容更新的重新驗(yàn)證。編輯內(nèi)容時要觸發(fā)的事件是object.edited.published。Webhook URL 端點(diǎn)將如下所示:${YOUR_VERCEL_DEPLOYMENT_URL}/api/revalidate。
這也使得在創(chuàng)建或更新來自無頭部的CMS 的內(nèi)容時,你的網(wǎng)站更容易更新。
現(xiàn)在來測試一下,在 Cosmic 面板中編輯內(nèi)容,并查看靜態(tài)內(nèi)容立即更新。
結(jié)論
現(xiàn)在,你已擁有一個動態(tài)的、可定制的、完全集成的模板,其中包含新的 Next.js 和 Cosmic 功能。你可以為其他類型的企業(yè)定制,并按照自己的喜好來使用。
譯者介紹
吳河?xùn)|,社區(qū)編輯,具有5年工作經(jīng)驗(yàn),從事電商相關(guān)IT工作。擅長后臺開發(fā),大數(shù)據(jù),算法等。
原文標(biāo)題:??Build a Production Ready Restaurant Website with Next.js 12 and Cosmic??,作者:Naira Gezhoyan
本文標(biāo)題:使用 Next.js 12 和 Cosmic 構(gòu)建一個可以上線的餐廳網(wǎng)站
文章源于:http://www.dlmjj.cn/article/dppcshc.html


咨詢
建站咨詢
