next plugin preval
v1.2.6
빌드 타임에서 비동기 함수 (데이터 페치 용) 사전 평가 및 JSON처럼 가져 오기
// data.preval.js (or data.preval.ts)
// step 1: create a data.preval.js (or data.preval.ts) file
import preval from 'next-plugin-preval' ;
// step 2: write an async function that fetches your data
async function getData ( ) {
const { title , body } = await /* your data fetching function */ ;
return { title , body } ;
}
// step 3: export default and wrap with `preval()`
export default preval ( getData ( ) ) ; // Component.js (or Component.ts)
// step 4: import the preval
import data from './data.preval' ;
// step 5: use the data. (it's there synchronously from the build step!)
const { title , body } = data ;
function Component ( ) {
return (
< >
< h1 > { title } </ h1 >
< p > { body } </ p >
</ >
) ;
}
export default Component ; 다음 메커니즘 Next.js는 정적 데이터를 제공하는 getStaticProps 입니다. 이는 훌륭한 기능이며 많은 사용 사례에 적합한 도구입니다. 그러나 getStaticProps 가 다루지 않는 정적 데이터의 다른 사용 사례가 있습니다.
getStaticProps 각각의 새 페이지마다 동일한 정적 데이터를 다시 가져와야하기 때문에 다소 어색한 메커니즘입니다. 예를 들어, getStaticProps 사용하여 헤더의 콘텐츠를 가져 오면 해당 데이터가 모든 페이지 변경마다 다시 가져옵니다.getStaticProps next-plugin-preval 과 함께 API 노선에서는 작동하지 않습니다.next-plugin-preval JSON 가져 오기와 같은 동작이므로 번들러가 표준 정적 자산을 가져 오기위한 최적화를 활용할 수 있습니다. 여기에는 표준 코드 분할 및 파괴가 포함됩니다.구체적인 예제는 레시피를 참조하십시오.
yarn add next-plugin-preval
또는
npm i next-plugin-preval
// next.config.js
const createNextPluginPreval = require ( 'next-plugin-preval/config' ) ;
const withNextPluginPreval = createNextPluginPreval ( ) ;
module . exports = withNextPluginPreval ( /* optionally add a next.js config */ ) ; 확장자 .preval.ts 또는 .preval.js 로 파일을 만듭니다 preval()
// my-data.preval.js
import preval from 'next-plugin-preval' ;
async function getData ( ) {
return { hello : 'world' ; }
}
export default preval ( getData ( ) ) ;그런 다음 해당 파일을 어디서나 가져옵니다. 약속의 결과가 반환됩니다.
// component.js (or any file)
import myData from './my-data.preval' ; // ? this is effectively like importing JSON
function Component ( ) {
return (
< div >
< pre > { JSON . stringify ( myData , null , 2 ) } </ pre >
</ div >
) ;
}
export default Component ; .preval 파일을 가져 오면 JSON을 가져 오는 것과 같습니다. next-plugin-preval 빌드 중에 기능을 실행하고 JSON Blob을 모듈로 인라인으로 실행합니다.
이것은 코드를 가져 와서 컴파일하고 Node.js에서 실행하는 웹 팩 로더를 통해 작동합니다.
require('next') 통해이 맥락을 조롱하기 위해 최선을 다합니다. 대부분의 데이터 쿼리의 경우 충분해야하지만 문제가 발생하면 문제를 열어주십시오. // header-data.preval.js
import preval from 'next-plugin-preval' ;
async function getHeaderData ( ) {
const headerData = await /* your data fetching function */ ;
return headerData ;
}
export default preval ( getHeaderData ( ) ) ; // header.js
import headerData from './header-data.preval' ;
const { title } = headerData ;
function Header ( ) {
return < header > { title } </ header > ;
}
export default Header ; // products.preval.js
import preval from 'next-plugin-preval' ;
async function getProducts ( ) {
const products = await /* your data fetching function */ ;
// create a hash-map for O(1) lookups
return products . reduce ( ( productsById , product ) => {
productsById [ product . id ] = product ;
return productsById ;
} , { } ) ;
}
export default preval ( getProducts ( ) ) ; // /pages/api/products/[id].js
import productsById from '../products.preval.js' ;
const handler = ( req , res ) => {
const { id } = req . params ;
const product = productsById [ id ] ;
if ( ! product ) {
res . status ( 404 ) . end ( ) ;
return ;
}
res . json ( product ) ;
} ;
export default handler ; // states.preval.js
import preval from 'next-plugin-preval' ;
async function getAvailableStates ( ) {
const states = await /* your data fetching function */ ;
return states ;
}
export default preval ( getAvailableStates ( ) ) ; // state-picker.js
import { useState , useEffect } from 'react' ;
function StatePicker ( { value , onChange } ) {
const [ states , setStates ] = useState ( [ ] ) ;
useEffect ( ( ) => {
// ES6 dynamic import
import ( './states.preval' ) . then ( ( response ) => setStates ( response . default ) ) ;
} , [ ] ) ;
if ( ! states . length ) {
return < div > Loading… </ div > ;
}
return (
< select value = { value } onChange = { onChange } >
{ states . map ( ( { label , value } ) => (
< option key = { value } value = { value } >
{ label }
</ option >
) ) }
</ select >
) ;
} 메모에 명시된 바와 같이, 다음 플루그 핀-프레 발의 결과는 빌드를 떠난 후에는 변경되지 않습니다. 그러나 데이터 가져 오기 기능을 추출하고 미리보기 모드를 기반으로 조건부로 호출하는 경우 ( context.preview 를 통해. 미리보기 모드가 활성화되지 않은 경우 기본적으로 유행 파일을 기본적으로 할 수 있습니다.
// get-data.js
// 1. extract a data fetching function
async function getData ( ) {
const data = await /* your data fetching function */ ;
return data
} // data.preval.js
import preval from 'next-plugin-preval' ;
import getData from './getData' ;
// 2. use that data fetching function in the preval
export default preval ( getData ( ) ) ; // /pages/some-page.js
import data from './data.preval' ;
import getData from './get-data' ;
export async function getStaticProps ( context ) {
// 3. conditionally call the data fetching function defaulting to the prevalled version
const data = context . preview ? await getData ( ) : data ;
return { props : { data } } ;
} next-data-hooks - getStaticProps React Hooks로 사용하는 패턴을 만듭니다. 미리보기 모드 또는 ISR이 필요한 경우 사이트 전체 데이터 케이스에 적합합니다.