다음을 구축하고 배치합니다.Kentico Kontent 및 Vercel의 js 블로그

Kentico Kontent 헤드 없는 CMS의 모든 이점을 제공하는 동시에 마케팅 팀이 디지털 채널을 관리할 수 있는 환경을 제공합니다.
이 설명서는 Kontent를 Next와 함께 사용하는 방법을 보여 줍니다.jsStatic Generation는 Kontent 데이터에서 정적 페이지를 생성하여 사용자에게 번개 같은 체험을 제공합니다.

Following text is an extended explanation of the Statically generated blog using Next.js and Kontent repository.


첫 번째 단계: Kontent+ 다음 단계를 만듭니다.js 프로젝트


다음 화면 캡처와 같이 view a working demo 프로그램을 만들 수 있습니다.

다음.js+Kontent 데모 응용 프로그램.


Kontent 프로젝트 등록


시작할 때create an account on Kontent.ai.등록 후create an empty project.

내용 모형을 만들고 데이터로 채우기


content model는 응용 프로그램/사이트의 데이터 구조를 정의했다.이런 구조들은 매우 유연해서 너는 자신의 수요에 따라 조정할 수 있다.
이 예에 대해 정의authorpost 내용 유형의 내용 모델을 만들어야 합니다.

You can create the content model and fill it with data manually to familiarize yourself with the Kontent user interface.


컨텐츠 모델과 데이터를 자동으로 가져오려면 다음 절차를 따르십시오.
  • 입력Kontent application
  • 프로젝트 설정에 들어가고 API 키
  • 를 선택합니다.
  • 관리 API 활성화
  • 사본Project ID 및 키Management API
  • 설치 Kontent Backup Manager 및 데이터를 kontent-backup.zip 파일에서 새로 생성된 항목apiKeyprojectId 매개변수에 적합한 값으로 가져옵니다.
  • npm i -g @kentico/kontent-backup-manager
    kbm --action=restore --apiKey=<Management API key> --projectId=<Project ID> --zipFilename=kontent-backup
    

    💡 Alternatively, you can use the Template Manager UI for importing the content.

  • Kontent 프로젝트로 이동하여 가져온 모든 프로젝트를 게시합니다.
    > 더 이상 필요 없는 관리 API를 비활성화할 수 있습니다.
  • 애플리케이션 초기화


    다음 명령을 사용하여 로컬 응용 프로그램을 초기화합니다.
    npm init next-app --example cms-kontent nextjs-kontent-app && cd nextjs-kontent-app
    

    Initializing a Next.js + Kontent app and entering the project directory.


    2단계: 환경 변수 설정


    이 디렉토리의 .env.local.example 파일을 .env.local에 복사합니다(Git에서는 무시됨).
    그런 다음 키.env.local>Project settings를 사용하여 각 변수를 onAPI keys으로 설정합니다.
  • KONTENT_PROJECT_ID - Project settings>API keys의 프로젝트 ID여야 합니다.
  • KONTENT_PREVIEW_API_KEY > Project settings의 미리보기 API 키 중 하나입니다.
  • API keys - 임의의 문자열일 수 있지만 빈칸은 피해야 한다. 예를 들어 KONTENT_PREVIEW_SECRET - 이것은 Preview Mode에 사용된다.
  • 필요한 의존항이 설치되면 다음 항목을 실행하고 개발할 수 있습니다.로컬 js+Kontent 응용 프로그램입니다.
    npm install
    npm run dev
    
    yarn
    yarn dev
    

    3단계: 코드 이해


    어플리케이션의 작동 방식을 이해하려면 다음 세 가지 주요 영역을 탐색해야 합니다.
  • Page Setup
  • Retrieving Content
  • Image Optimization
  • 페이지 설정


    각 페이지에는 두 개의 최신 블로그 기사(각 페이지에는 두 개의 기사)가 표시됩니다.
    import { useRouter } from 'next/router'
    import ErrorPage from 'next/error'
    import Container from '../../components/container'
    import PostBody from '../../components/post-body'
    import MoreStories from '../../components/more-stories'
    import Header from '../../components/header'
    import PostHeader from '../../components/post-header'
    import SectionSeparator from '../../components/section-separator'
    import Layout from '../../components/layout'
    import {
      getAllPostSlugs,
      getPostBySlug,
      getMorePostsForSlug,
    } from '../../lib/api'
    import PostTitle from '../../components/post-title'
    import Head from 'next/head'
    import { CMS_NAME } from '../../lib/constants'
    
    export default function Post({ post, morePosts = [], preview }) {
      const router = useRouter()
      if (!router.isFallback && !post?.slug) {
        return <ErrorPage statusCode={404} />
      }
      return (
        <Layout preview={preview}>
          <Container>
            <Header />
            {router.isFallback ? (
              <PostTitle>Loading…</PostTitle>
            ) : (
              <>
                <article className="mb-32">
                  <Head>
                    <title>
                      {post.title} | Next.js Blog Example with {CMS_NAME}
                    </title>
                    <meta property="og:image" content={post.coverImage.url} />
                  </Head>
                  <PostHeader
                    title={post.title}
                    coverImage={post.coverImage}
                    date={post.date}
                    author={post.author}
                  />
                  <PostBody content={post.content} />
                </article>
                <SectionSeparator />
                {morePosts.length > 0 && <MoreStories posts={morePosts} />}
              </>
            )}
          </Container>
        </Layout>
      )
    }
    
    export async function getStaticProps({ params, preview = null }) {
      return await Promise.all([
        getPostBySlug(params.slug, preview),
        getMorePostsForSlug(params.slug, preview),
      ]).then((values) => ({
        props: {
          post: values[0],
          morePosts: values[1],
          preview,
        },
      }))
    }
    
    export async function getStaticPaths() {
      const slugs = await getAllPostSlugs(['slug'])
      return {
        paths: slugs.map(
          (slug) =>
            ({
              params: {
                slug,
              },
            } || [])
        ),
        fallback: false,
      }
    }
    

    The pages/posts/[slug].js file for your Next.js +
    Kontent app.


    컨텐츠 검색

    MY_SECRET 파일에서 Kontent 데이터를 검색하고 Kontent Delivery SDK를 사용하여 Kontent 제공 API에 요청합니다.
    import { DeliveryClient } from '@kentico/kontent-delivery'
    import { name, version } from '../package.json'
    
    const sourceTrackingHeaderName = 'X-KC-SOURCE'
    
    const client = new DeliveryClient({
      projectId: process.env.KONTENT_PROJECT_ID,
      previewApiKey: process.env.KONTENT_PREVIEW_API_KEY,
      globalHeaders: (_queryConfig) => [
        {
          header: sourceTrackingHeaderName,
          value: `@vercel/next.js/example/${name};${version}`,
        },
      ],
    })
    
    function parseAuthor(author) {
      return {
        name: author.name.value,
        picture: author.picture.value[0].url,
      }
    }
    
    function parsePost(post) {
      return {
        title: "post.title.value,"
        slug: post.slug.value,
        date: post.date.value.toISOString(),
        content: post.content.value,
        excerpt: post.excerpt.value,
        coverImage: post.cover_image.value[0].url,
        author: parseAuthor(post.author.value[0]),
      }
    }
    
    export async function getAllPostSlugs() {
      const postsResponse = await client
        .items()
        .type('post')
        .elementsParameter(['slug'])
        .toPromise()
    
      return postsResponse.items.map((post) => post.slug.value)
    }
    
    export async function getMorePostsForSlug(slug, preview) {
      return client
        .items()
        .queryConfig({
          usePreviewMode: !!preview,
        })
        .type('post')
        .orderByDescending('elements.date')
        .withParameter('elements.slug[neq]', slug)
        .limitParameter(2)
        .toPromise()
        .then((res) => {
          return res.items.map((post) => parsePost(post))
        })
    }
    
    export async function getPostBySlug(slug, preview) {
      const post = await client
        .items()
        .queryConfig({
          usePreviewMode: !!preview,
        })
        .type('post')
        .equalsFilter('elements.slug', slug)
        .toPromise()
        .then((result) => result.getFirstItem())
        .then((post) => parsePost(post))
      return post
    }
    
    export async function getAllPosts(preview) {
      return await client
        .items()
        .queryConfig({
          usePreviewMode: !!preview,
        })
        .type('post')
        .orderByDescending('elements.date')
        .toPromise()
        .then((postsResponse) => postsResponse.items.map((post) => parsePost(post)))
    }
    

    The lib/api.js file for your Next.js + Kontent app.


    이미지 변환 가능성


    웹 사이트의 속도를 최적화하려면 Kontent Image Transformation API를 사용하여 검색한 이미지를 변환하고 다운로드 시간을 줄일 수 있습니다.이것은 블로그 게시물의 표지 사진이나 작가의 개인 자료 사진에 적용될 수 있다.가장 간단한 방법은 사용Image transformation support in Kontent Delivery SDK이다.
    import cn from 'classnames'
    import Link from 'next/link'
    import {
      ImageUrlBuilder,
      ImageCompressionEnum,
      ImageFormatEnum,
    } from '@kentico/kontent-delivery'
    
    export default function CoverImage({ title, src, slug }) {
      const transformedSrc = new ImageUrlBuilder(src)
        .withCompression(ImageCompressionEnum.Lossless)
        .withAutomaticFormat(ImageFormatEnum.Webp)
        .withQuality(80)
        .getUrl()
    
      const image = (
        <img
          src={transformedSrc}
          alt={`Cover Image for ${title}`}
          className={cn('shadow-small', {
            'hover:shadow-medium transition-shadow duration-200': slug,
          })}
        />
      )
      return (
        <div className="-mx-5 sm:mx-0">
          {slug ? (
            <Link as={`/posts/${slug}`} href="/posts/[slug]">
              <a aria-label={title}>{image}</a>
            </Link>
          ) : (
            image
          )}
        </div>
      )
    }
    

    Possible modification of components/cover-image.js
    component using Image Transformation API to get images in
    modern WebP format.


    4단계: 미리 보기 모드 사용


    Preview Delivery API를 사용하여 Kontent 프로젝트 내용을 미리 보는 기능을 추가하려면 Kontent 프로젝트를 열고 프로젝트 설정 > 미리 보기 URL에 들어가서 slug 내용 유형의 새 미리 보기 URL을 다음과 같이 설정합니다.
    http://localhost:3000/api/preview?secret=<KONTENT_PREVIEW_SECRET>&slug={URLslug}
    

    Replace <KONTENT_PREVIEW_SECRET> with its respective value in .env.local:



    저장한 후 작성한 게시물 중 하나로 이동하고 다음을 수행합니다.
  • 게시물의 새 버전 만들기

  • 제목을 업데이트합니다.예를 들어, 제목 앞에 lib/api.js를 추가할 수 있습니다.
    > 제목도 URL 세그먼트 마개가 재생성됩니다. URL 세그먼트 마개에 영향을 주지 않는 다른 필드를 변경하려면 원하는 대로 변경하십시오.

  • 발표하지 마.이렇게 하면 게시물이 초안 워크플로우 단계로 이동합니다.
  • 메뉴에서 미리 보기 단추를 볼 수 있습니다.클릭하세요!

  • 현재 업데이트된 제목을 볼 수 있습니다.미리보기 모드를 종료하려면 페이지 맨 위에 있는 여기를 클릭하여 미리보기 모드를 종료합니다.

    5단계: Vercel을 사용하여 어플리케이션 배포


    다음을 배치하다.js+Kontent 사이트는 Vercel for Git와 통합되어 Git 저장소로 전송되었는지 확인합니다.
    가져오는 동안 다음 환경 변수를 추가해야 합니다.
  • KONTENT 프로젝트 ID
  • KONTENT 미리보기 API 키
  • KONTENT_PREVIEW_SECRET
  • 선택한 Git 통합을 사용하여 프로젝트를 Vercel로 가져오려면 다음과 같이 하십시오.
  • GitHub
  • GitLab
  • Bitbucket
  • 프로젝트를 가져오면 모든 후속 전송 지점의 작업은 미리 보기 배치를 생성하고 생산 지점(일반적으로 "main")에 대한 모든 변경 사항은 생산 배치를 생성합니다.
    배포 후 사이트를 실시간으로 볼 수 있는 URL이 제공됩니다(예: https://next-blog-kontent.vercel.app/.
    다음을 설정합니다.Deploy 단추를 사용하여 js+Kontent 사이트를 몇 번 클릭하고 업데이트된 자동 배치 과정에서 Git 저장소를 만듭니다.

    If you want to explore a more complex example for Kentico Kontent and Next.js, check out this Corporate Starter.

    케티코 / kontent starter corporate next js

    다음.js corporate starter 웹 사이트는 Kentico Kontent를 데이터 소스로 사용합니다.


    좋은 웹페이지 즐겨찾기