从任何地方获取数据,包括Next.js,Nuxt.js,Eleventy等
从任何地方获取数据,包括Next.js,Nuxt.js,Eleventy等
JavaScript 其它杂项
共201Star
详细介绍
🤺
Mordred
Source data from anywhere, for Next.js, Nuxt.js, Eleventy and many more.
Features
Table of Contents
Install
yarn add mordred
Usage with Next.js
Configuration
In next.config.js
:
module.exports = {
webpack(config) {
const { MordredWebpackPlugin } = require('mordred/webpack')
const mordredPlugin = new MordredWebpackPlugin()
config.plugins.push(mordredPlugin)
return config
},
}
Then create a mordred.config.js
in the same directory and use some plugins:
module.exports = {
plugins: [
{
resolve: 'mordred-source-filesystem',
options: {
// This is where you'll be creating Markdown files
path: __dirname + '/content',
},
},
{
resolve: 'mordred-transformer-markdown',
},
],
}
You also need to install these plugins:
yarn add mordred-source-filesystem mordred-transformer-markdown
Using Data
Create a Markdown file in content
folder (in your project root), like content/my-first-posts.md
:
---
title: My First Post
date: 2020-04-24
---
This is my **first** post!
When you run next
or next build
, Mordred will generate a GraphQL client at mordred/graphql.js
, then you can use the generated client to query data.
Now in any page, query data in getStaticProps
:
import { query, gql } from '../mordred/graphql'
export const getStaticProps = async () => {
const { data, errors } = await query(gql`
{
allMarkdown {
nodes {
id
slug
createdAt
updatedAt
html
frontmatter {
# ... or any frontmatter
# like:
title
}
}
}
}
`)
if (errors) {
throw errors[0]
}
return {
props: {
...data,
},
}
}
export default ({ allMarkdown }) => {
return (
<ul>
{allMarkdown.nodes.map((post) => {
return (
<li key={post.id}>
<Link href={`/post/${post.slug}`}>{post.title}</Link>
</li>
)
})}
</ul>
)
}
Exploring Data with GraphiQL
You can create an API at /api/graphql
to explore data via 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
Usage With Nuxt.js
We're waiting for Nuxt's full-static mode, it's already possible to use Mordred with Nuxt's asyncData
though. We'll document this soon.
Plugin List
License
MIT © EGOIST (Kevin Titor)
-
251 Star
-
33 Star
-
2387 Star
-
2 Star
-
0 Star
-
664 Star
-
43 Star
-
0 Star