來自任何地方的源數據
✅受Gatsby的啟發,您可以使用GraphQL查詢任何數據(Markdown,API,數據庫,CMS)
✅自動生成JavaScript客戶端以獲得更好的開發體驗
✅框架不可知論,可與具有SSG支持的任何框架一起使用
✅流行無頭CM的大量插件(還不,我們需要您的貢獻!)
yarn add mordred在next.config.js中:
const { withMordred } = require ( 'mordred/next' )
module . exports = withMordred ( {
// Extra Next.js config..
} )然後在同一目錄中創建mordred.config.js ,並使用一些插件:
module . exports = {
plugins : [
// Load markdown files from file system
{
resolve : 'mordred-source-filesystem' ,
options : {
// This is where you'll be creating Markdown files
path : __dirname + '/content' ,
} ,
} ,
// Transform files to markdown nodes
{
resolve : 'mordred-transformer-markdown' ,
} ,
] ,
}您還需要安裝這些插件:
yarn add mordred-source-filesystem mordred-transformer-markdown在content文件夾(在您的項目root中)中創建一個標記文件,例如content/my-first-posts.md :
---
title : My First Post
date : 2020-04-24
---
This is my ** first ** post!當您next或next build運行時,Mordred將在mordred/graphql.js上生成一個GraphQl客戶端,然後您可以使用生成的客戶端查詢數據。
您應該將此文件夾添加到.gitignore :
mordred/
現在在任何頁面中,查詢getStaticProps中的數據:
import { client } from '../mordred/graphql'
export const getStaticProps = async ( ) => {
const { allMarkdown } = await client . query ( {
allMarkdown : [
{
limit : 20
} ,
{
nodes : {
id : true ,
slug : true ,
createdAt : true ,
updatedAt : true ,
html : true ,
frontmatter {
title : true
}
}
}
]
} )
return {
props : {
allMarkdown
} ,
}
}
export default ( { allMarkdown } ) => {
return (
< ul >
{ allMarkdown . nodes . map ( ( post ) => {
return (
< li key = { post . id } >
< Link href = { `/post/ ${ post . slug } ` } > { post . title } </ Link >
</ li >
)
} ) }
</ ul >
)
} client.query語法與graphQl sdl非常相似,除了它在編寫時還提供了類型提示,我們使用graphql-zeus來生成客戶端代碼。
如果您更喜歡GraphQl SDL而不是JavaScript客戶端,則也可以執行原始查詢:
import { executeQuery , gql } from './path/to/mordred/graphql'
const { data , errors } = await executeQuery (
gql `
query($limit: Int!) {
allMarkdown(limit: $limit) {
id
}
}
` ,
{
limit : 20 ,
} ,
)請注意,我們在此處僅使用gql標籤來進行語法突出顯示,例如VS代碼(VS Code),它是完全可選的。
當您的項目具有深嵌套文件夾結構時,您可能會遇到導入地獄:
import { client } from '../../mordred/graphql'為了簡化導入路徑,您可以在tsconfig.json中使用paths選項:
{
"compilerOptions" : {
"baseUrl" : " . " ,
"paths" : {
"mordred-graphql" : [ " ./mordred/graphql " ]
}
}
}現在,您可以代替導入mordred-graphql 。
請注意,Next.js默認支持paths ,但是如果您使用其他不支持此的工具,則可能會發現別名HQ有用。
您可以創建一個API AT /api/graphql ,以通過GraphIQL探索數據:
import express from 'express'
import graphqlHTTP from 'express-graphql'
import { schema } from '../../mordred/graphql'
const app = express ( )
app . use (
graphqlHTTP ( {
schema ,
graphiql : true ,
} ) ,
)
export default app 麻省理工學院©Egoist(Kevin Titor)