来自任何地方的源数据
✅受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)