Using the Flexible Gatsby starter (https://github.com/wangonya/flexible-gatsby/), exact versions of Gatsby dependencies are:
"gatsby": "2.15.36",
"gatsby-image": "2.2.27",
"gatsby-plugin-feed": "2.3.15",
"gatsby-plugin-google-analytics": "2.1.20",
"gatsby-plugin-manifest": "2.2.20",
"gatsby-plugin-offline": "3.0.12",
"gatsby-plugin-react-helmet": "3.1.10",
"gatsby-plugin-sass": "2.1.17",
"gatsby-plugin-sharp": "2.2.28",
"gatsby-remark-images": "3.1.25",
"gatsby-remark-prismjs": "3.3.17",
"gatsby-source-filesystem": "2.1.30",
"gatsby-transformer-remark": "2.6.27",
"gatsby-transformer-sharp": "2.2.20",
I can run gatsby develop to get a watch on the files in the folder that refreshes UI changes and such. However, as soon as I save any changes to any of the files in content/blog develop hits the following error:
info added file at /Users/mattsi/dev/me/newsite/gatsby/content/blog/conference-on-javascript/index.md
ERROR #11321 PLUGIN
"gatsby-node.js" threw an error while running the createPages lifecycle:
The "path" argument must be of type string. Received type undefined
GraphQL request:14:17
13 | title
14 | img {
| ^
15 | childImageSharp {
After that, the local server responds with an error page saying TypeError: Cannot read property 'page' of undefined and a stack trace pointing to rootjs:44. If I kill the watch and do gatsby develop again, it works fine. But that feedback loop is obviously much slower.
My Gatsby Config (some details omitted with ...):
module.exports = {
siteMetadata: {
title: `...`,
description: `...`,
author: `...`,
siteUrl: `...`,
social: {
twitter: `...`,
facebook: ``,
github: `...`,
linkedin: `...`,
email: `...`,
},
},
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/content/blog`,
name: `blog`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/content/assets`,
name: `assets`,
},
},
{
resolve: `gatsby-transformer-remark`,
options: {
plugins: [
{
resolve: `gatsby-remark-images`,
options: {
maxWidth: 970,
},
},
`gatsby-remark-prismjs`,
],
},
},
`gatsby-transformer-sharp`,
`gatsby-plugin-sharp`,
{
resolve: `gatsby-plugin-google-analytics`,
options: {
//trackingId: `ADD YOUR TRACKING ID HERE`,
},
},
`gatsby-plugin-feed`,
{
resolve: `gatsby-plugin-manifest`,
options: {
name: `...`,
short_name: `...`,
start_url: `/`,
background_color: `#663399`,
theme_color: `#663399`,
display: `minimal-ui`,
icon: `./static/gatsby-icon.png`, // This path is relative to the root of the site.
},
},
// `gatsby-plugin-offline`,
`gatsby-plugin-react-helmet`,
`gatsby-plugin-sass`,
],
}
My gatsby-node.js file:
const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions
const blogPost = path.resolve(`./src/templates/blog-post.js`)
return graphql(
`
{
allMarkdownRemark(
sort: { fields: [frontmatter___date], order: DESC }
limit: 1000
) {
edges {
node {
fields {
slug
}
frontmatter {
title
img {
childImageSharp {
fluid(maxWidth: 3720) {
aspectRatio
base64
sizes
src
srcSet
}
}
}
}
}
}
}
}
`
).then(result => {
if (result.errors) {
throw result.errors
}
// Create blog posts pages.
const posts = result.data.allMarkdownRemark.edges
posts.forEach((post, index) => {
const previous = index === posts.length - 1 ? null : posts[index + 1].node
const next = index === 0 ? null : posts[index - 1].node
createPage({
path: post.node.fields.slug,
component: blogPost,
context: {
slug: post.node.fields.slug,
previous,
next,
},
})
})
// Create blog post list pages
const postsPerPage = 10
const numPages = Math.ceil(posts.length / postsPerPage)
Array.from({ length: numPages }).forEach((_, i) => {
createPage({
path: i === 0 ? `/` : `/${i + 1}`,
component: path.resolve("./src/templates/blog-list.js"),
context: {
limit: postsPerPage,
skip: i * postsPerPage,
numPages,
currentPage: i + 1,
},
})
})
})
}
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const value = createFilePath({ node, getNode })
createNodeField({
name: `slug`,
node,
value,
})
}
}
Looking into the stack trace, it seems as if the post.node.fields.slug field on the modified post from the allMarkdownRemark GraphQL DB is coming back as undefined. But using the built-in GraphQL browser it seems to always be populated. Perhaps it's very briefly unpopulated while refreshing, faster than I can catch, and this causes the watch to crash? Any ideas how I can fix Gatsby's watch functionality?
I have this issue too and I believe it will be fixed by this PR - it was for me at least. Perhaps you could test it out and comment on the PR if it helps you.
Related
I am trying to use createRemoteFileNode to create optimised images for an array of nodes that exist on a Product.
I have a Product that has items and on each item, it has a featuredImg. I can create a featuredImg for a Product but as soon as I try to create it for the child nodes (items) then it is not queryable.
I am creating my nodes as such:
const products = [
{
id: "product_1",
imageUrl: "https://images.unsplash.com/photo-1665081661649-8656335a6cbb?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1738&q=80",
items: [
{
id: 'item_1',
imageUrl: "https://images.unsplash.com/photo-1666120565124-7e763880444a?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1770&q=80"
}
]
}
]
const sourceNodes = async ({ actions, createNodeId, createContentDigest }, options) => {
products.forEach((testNode) => {
const node = {
...testNode,
id: createNodeId(`Product-${testNode.id}`),
}
actions.createNode({
...node,
internal: {
type: 'Product',
contentDigest: createContentDigest(node),
},
});
testNode.items.forEach(item => {
const itemNode = {
...item,
id: createNodeId(`Item-${item.id}`),
}
actions.createNode({
...itemNode,
parent: node.id,
internal: {
type: 'Item',
contentDigest: createContentDigest(itemNode),
},
});
})
})
};
module.exports = sourceNodes;
Then on the node creation, I am running the onCreateNode function which should create the remote file node for each item featuredImg.
const { createRemoteFileNode } = require(`gatsby-source-filesystem`);
const onCreateNode = async ({ node, cache, store, getCache, actions: { createNode, createNodeField }, createNodeId }) => {
if( node.internal.type === 'Item') {
const fileNode = await createRemoteFileNode({
url: node.imageUrl,
parentNodeId: node.parent,
createNode,
createNodeId,
getCache,
})
if (fileNode) {
createNodeField({ node, name: "localFile", value: fileNode.id })
}
}
if( node.internal.type === 'Product') {
const fileNode = await createRemoteFileNode({
url: node.imageUrl,
parentNodeId: node.id,
createNode,
createNodeId,
getCache,
})
if (fileNode) {
createNodeField({ node, name: "localFile", value: fileNode.id })
}
}
};
module.exports = onCreateNode
I have defined my types here:
module.exports = ({ actions }) => {
const { createTypes } = actions;
const typeDefs = `
type Product implements Node {
id: String!
imageUrl: String!
featuredImg: File #link(from: "fields.localFile")
items: [Item]
}
type Item implements Node {
id: String!
imageUrl: String!
featuredImg: File #link(from: "fields.localFile")
}
`;
createTypes(typeDefs);
};
For some reason, when I query Products.items[i].featuredImg it always returns null. However, I can see the node is generated because I can query item.featuredImg and it returns the gatsbyImageData.
I have created a simple example here and included a read me on how to replicate it: https://github.com/stretch0/gatsby-sandbox
I have also noticed that this post is a similar issue of not being able to create remote file nodes within a loop but because they have a different file structure, I can't figure out how their solution to use createSchemaCustomization or createResolvers would apply to my setup.
Navigating to url: site.com/#locallink 'redirects' to site.com, first time entered in the browser - in other words, does not jump to the anchor.
If I simply re-type the url (site.com/#locallink) then it works as expected (jumps to anchor).
I have defined routes and router like so, and history mode as you can see.
let router = new VueRouter({
mode: 'history',
scrollBehavior: function (to, from, savedPosition) {
if (to.hash) {
return { selector: to.hash }
} else {
return { x: 0, y: 0 }
}
},
routes
});
If I have a link on another page to the same anchor, then it works flawlessly. It's only when typed into the browser directly that it does not seem to work - the # part of it get's eaten.
The routes follow this pattern:
export const routes = [
{
path: '/',
name: 'home',
component: require('components/prelogin/landingpage.vue'),
meta: {
title: 'Some title',
metaTags: [
{
name: 'title',
content: '...'
},
{
name: 'description',
content: 'some description here...'
}
]
}
},
...
There are many entries so only showing first.
Any ideas?
Thanks
Hope it will help
scrollBehavior: function (to, from, savedPosition) {
if (to.hash){
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve({
selector: to.hash,
behavior: 'smooth',
})
}, 500)
})
} else {
return { x: 0, y: 0 }
}
}
I have encountered a problem while making a personal Gatsby site whereby blog post files are having thier unique folders included in the slug.
For example a file structure of:
data
|
|– blog
|
|– blog-1
| |
| |-blog-1.mdx
| |-img.jpg
|
|– blog-2
| |
| |-blog-2.mdx
| |-img.jpg
|
|– blog-3
| |
| |-blog-3.mdx
| |-img.jpg
Will, for example, produce slugs like this
{
"data": {
"allMdx": {
"edges": [
{
"node": {
"fields": {
"slug": "/blog-1/blog-1/"
},
"frontmatter": {
"title": "Blog 1",
"posttype": "blog"
}
}
},
{
"node": {
"fields": {
"slug": "/blog-2/blog-2/"
},
"frontmatter": {
"title": "Blog 2",
"posttype": "blog"
}
}
},
{
"node": {
"fields": {
"slug": "/blog-3/blog-3/"
},
"frontmatter": {
"title": "Blog 3",
"posttype": "blog"
}
}
},
I expect them to produce a slug like this:
{
"node": {
"fields": {
"slug": "/blog-1/"
},
"frontmatter": {
"title": "Blog 1",
"posttype": "blog"
}
}
},
The path to the parent blog folder is included in my gatsby-config like this:
{
resolve: `gatsby-source-filesystem`,
options: {
path: `${__dirname}/data/blog`,
name: `blog`,
},
},
And then my gatsby-node folder is set up like this:
const path = require(`path`)
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions
const blogPost = path.resolve(`./src/templates/blog-post.js`)
const portfolioPost = path.resolve(`./src/templates/portfolio-post.js`)
const journeyPost = path.resolve(`./src/templates/journey-post.js`)
return graphql(
`
{
allMdx(
sort: { fields: [frontmatter___date], order: DESC }
limit: 1000
) {
edges {
node {
fields {
slug
}
frontmatter {
title
posttype
}
}
}
}
}
`
).then(result => {
if (result.errors) {
throw result.errors
}
const posts = result.data.allMdx.edges
posts.forEach((post, index) => {
const previous = index === posts.length - 1 ? null : posts[index + 1].node
const next = index === 0 ? null : posts[index - 1].node
if (post.node.frontmatter.posttype == "portfolio") {
createPage({
path: `/portfolio${post.node.fields.slug}`,
component: portfolioPost,
context: {
slug: post.node.fields.slug,
previous,
next,
},
})
} else if (post.node.frontmatter.posttype == "journey") {
createPage({
path: `/journey${post.node.fields.slug}`,
component: journeyPost,
context: {
slug: post.node.fields.slug,
previous,
next,
},
})
} else {
createPage({
path: `/blog${post.node.fields.slug}`,
component: blogPost,
context: {
slug: post.node.fields.slug,
previous,
next,
},
})
}
})
return null
})
}
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === `Mdx`) {
const value = createFilePath({ node, getNode })
createNodeField({
name: `slug`,
node,
value,
})
}
}
Note that the journey and portfolio paths in this file are at this point in time doing exactly the same thing as the blog path. They are set up in exactly the same way and are just split out depending on posttype. Pages are created fine but they are all using the unwanted folder/file.mdx slug.
Fixed by looking at other blog examples.
Post filename needs to be index.md or index.mdx
I am sure there is a better way but I was able to solve it by making changes in gatsby-node.js to only take the substring after the last slash (/) in from the file path. If someone knows a better way I will be glad to know that.
Old:
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const value = createFilePath({ node, getNode })
createNodeField({
name: `slug`,
node,
value,
})
}
}
New:
exports.onCreateNode = ({ node, actions, getNode }) => {
const { createNodeField } = actions
if (node.internal.type === `MarkdownRemark`) {
const value = createFilePath({ node, getNode, trailingSlash:false })
createNodeField({
name: `slug`,
node,
value: `${value.indexOf("/") > -1 ? value.substring(value.lastIndexOf("/")) : value}`,
})
}
}
Subscriptions with Nexus are undocumented but I searched Github and tried every example in the book. It's just not working for me.
I have cloned Prisma2 GraphQL boilerplate project & my files are as follows:
prisma/schema.prisma
datasource db {
provider = "sqlite"
url = "file:dev.db"
default = true
}
generator photon {
provider = "photonjs"
}
generator nexus_prisma {
provider = "nexus-prisma"
}
model Pokemon {
id String #default(cuid()) #id #unique
number Int #unique
name String
attacks PokemonAttack?
}
model PokemonAttack {
id Int #id
special Attack[]
}
model Attack {
id Int #id
name String
damage String
}
src/index.js
const { GraphQLServer } = require('graphql-yoga')
const { join } = require('path')
const { makeSchema, objectType, idArg, stringArg, subscriptionField } = require('#prisma/nexus')
const Photon = require('#generated/photon')
const { nexusPrismaPlugin } = require('#generated/nexus-prisma')
const photon = new Photon()
const nexusPrisma = nexusPrismaPlugin({
photon: ctx => ctx.photon,
})
const Attack = objectType({
name: "Attack",
definition(t) {
t.model.id()
t.model.name()
t.model.damage()
}
})
const PokemonAttack = objectType({
name: "PokemonAttack",
definition(t) {
t.model.id()
t.model.special()
}
})
const Pokemon = objectType({
name: "Pokemon",
definition(t) {
t.model.id()
t.model.number()
t.model.name()
t.model.attacks()
}
})
const Query = objectType({
name: 'Query',
definition(t) {
t.crud.findManyPokemon({
alias: 'pokemons'
})
t.list.field('pokemon', {
type: 'Pokemon',
args: {
name: stringArg(),
},
resolve: (parent, { name }, ctx) => {
return ctx.photon.pokemon.findMany({
where: {
name
}
})
},
})
},
})
const Mutation = objectType({
name: 'Mutation',
definition(t) {
t.crud.createOnePokemon({ alias: 'addPokemon' })
},
})
const Subscription = subscriptionField('newPokemon', {
type: 'Pokemon',
subscribe: (parent, args, ctx) => {
return ctx.photon.$subscribe.pokemon()
},
resolve: payload => payload
})
const schema = makeSchema({
types: [Query, Mutation, Subscription, Pokemon, Attack, PokemonAttack, nexusPrisma],
outputs: {
schema: join(__dirname, '/schema.graphql')
},
typegenAutoConfig: {
sources: [
{
source: '#generated/photon',
alias: 'photon',
},
],
},
})
const server = new GraphQLServer({
schema,
context: request => {
return {
...request,
photon,
}
},
})
server.start(() => console.log(`🚀 Server ready at http://localhost:4000`))
The related part is the Subscription which I don't know why it's not working or how it's supposed to work.
I searched Github for this query which results in all projects using Subscriptions.
I also found out this commit in this project to be relevant to my answer. Posting the related code here for brevity:
import { subscriptionField } from 'nexus';
import { idArg } from 'nexus/dist/core';
import { Context } from './types';
export const PollResultSubscription = subscriptionField('pollResult', {
type: 'AnswerSubscriptionPayload',
args: {
pollId: idArg(),
},
subscribe(_: any, { pollId }: { pollId: string }, context: Context) {
// Subscribe to changes on answers in the given poll
return context.prisma.$subscribe.answer({
node: { poll: { id: pollId } },
});
},
resolve(payload: any) {
return payload;
},
});
Which is similar to what I do. But they do have AnswerSubscriptionPayload & I don't get any generated type that contains Subscription in it.
How do I solve this? I think I am doing everything right but it's still not working. Every example on GitHub is similar to above & even I am doing the same thing.
Any suggestions?
Edit: Subscriptions aren't implemented yet :(
I seem to have got this working despite subscriptions not being implemented. I have a working pubsub proof of concept based off the prisma2 boilerplate and Ben Awad's video tutorial https://youtu.be/146AypcFvAU . Should be able to get this up and running with redis and websockets to handle subscriptions until the prisma2 version is ready.
https://github.com/ryanking1809/prisma2_subscriptions
Subscriptions aren't implemented yet.
I've opened up an issue to track it.
I'll edit this answer as soon as it's implemented in Prisma 2.
I have a Nuxt.js, statically generated site that has some dynamic pages. I'm using a GraphQL based headless CMS (DatoCMS) to provide the data for these pages, accessed using Apollo (#nuxt/apollo). I have it generating all the routes correctly but when I navigate to these pages from my site nav I'm receiving the following error 3 times:
TypeError: Cannot read property '_seoMetaTags' of undefined
at f.head (cf150f1920d36ab67139.js:1)
at wn.get (008dfc959ff6e6a713a0.js:2)
at wn.evaluate (008dfc959ff6e6a713a0.js:2)
at f.$metaInfo (008dfc959ff6e6a713a0.js:2)
at f.created (008dfc959ff6e6a713a0.js:2)
at Qt (008dfc959ff6e6a713a0.js:2)
at fn (008dfc959ff6e6a713a0.js:2)
at f.t._init (008dfc959ff6e6a713a0.js:2)
at new f (008dfc959ff6e6a713a0.js:2)
at 008dfc959ff6e6a713a0.js:2
This is coming from the head code in my page component so clearly something isn't being generated correctly. I can also see in the Chrome network tab that calls are being made to the GraphQL interface which also tells me the static generation isn't working correctly.
Here's the head() and apollo portions of my page component:
head() {
return {
title: this.blogPost._seoMetaTags.find(element => {
return element.tag === 'title';
}).content,
meta: [
{ hid: 'keywords', keywords: this.blogPost.keywords },
{ hid: 'description', description: this.blogPost._seoMetaTags.find(element => {
return element.tag === 'meta' && element.attributes.name === 'description';
}).attributes.content}
],
script: [
{ src: 'https://cdn.commento.io/js/commento.js', defer: true }
]
}
},
apollo: {
blogPost: {
query: gpl`
query BlogPost($slug: String!) {
blogPost(filter: { slug:{ eq: $slug }}) {
title
titleColor {
hex
}
slug
author
keywords
_seoMetaTags {
tag
attributes
content
}
_firstPublishedAt
banner {
id
url
title
}
content {
... on HeadingRecord {
_modelApiKey
heading
}
... on SubHeadingRecord {
_modelApiKey
subHeading
}
... on TextRecord {
_modelApiKey
content
}
... on CodeRecord {
_modelApiKey
codeBlock
}
... on ImageRecord {
_modelApiKey
image {
id
height
width
url
title
alt
}
}
... on VideoRecord {
_modelApiKey
video {
height
provider
providerUid
thumbnailUrl
title
url
width
}
}
}
}
}
`,
prefetch({ route }) {
return {
slug: route.params.slug
};
},
variables() {
return {
slug: this.$route.params.slug
};
}
And my nuxt.config.js if it helps:
const pkg = require('./package')
const webpack = require('webpack');
import fetch from 'node-fetch';
import { execute, makePromise } from 'apollo-link';
import { createHttpLink } from 'apollo-link-http';
import gql from 'graphql-tag';
module.exports = {
mode: 'universal',
/*
** Headers of the page
*/
head: {
title: pkg.name,
htmlAttrs: {
lang: 'en'
},
meta: [
{ charset: 'utf-8' },
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
{ hid: 'description', name: 'description', content: pkg.description }
],
link: [
{ rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' },
{ rel: 'stylesheet', href: 'https://cdn.jsdelivr.net/gh/tonsky/FiraCode#1.206/distr/fira_code.css' }
]
},
/*
** Customize the progress-bar color
*/
loading: { color: '#fff' },
/*
** Global CSS
*/
css: [
],
/*
** Plugins to load before mounting the App
*/
plugins: [
],
/*
** Nuxt.js modules
*/
modules: [
'#nuxtjs/style-resources',
'#nuxtjs/apollo',
'#nuxtjs/google-analytics'
],
/*
** #nuxtjs/google-analytics settings
*/
googleAnalytics: {
id: 'UA-136517294-1'
},
/*
** #nuxtjs/style-resources settings
*/
styleResources: {
scss: [
'./assets/css/*.scss'
]
},
/*
** Apollo setup for DatoCMS graphql queries
*/
apollo: {
includeNodeModules: true,
clientConfigs: {
default: '#/apollo/default.js'
}
},
/*
** Build configuration
*/
build: {
postcss: {
preset: {
features: {
customProperties: false
}
}
},
/*
** You can extend webpack config here
*/
extend(config, ctx) {
}
},
/*
** Generate configuration
*/
generate: {
routes: function(callback) {
// Get the list of posts
const uri = 'https://graphql.datocms.com';
const link = new createHttpLink({ uri: uri, fetch: fetch });
const operation = {
query: gql`
{
allBlogPosts {
id
slug
keywords
_seoMetaTags {
tag
attributes
content
}
}
}`,
context: {
headers: {
authorization: 'Bearer <my token>'
}
}
};
makePromise(execute(link, operation))
.then(data => {
// Build the routes from the posts
const postRoutes = data.data.allBlogPosts.map(item => {
return { route: `/blog/${item.slug}`, payload: { keywords: item.keywords, seoData: item._seoMetaTags }};
});
// Register the routes
callback(null, postRoutes);
})
.catch(error => console.log(`received error ${error}`));
}
}
}
If you expect all api requests to be bundled into app and not made anymore, thats not how nuxt currently work. It still will do requests to the api`s on client navigation withing app.
There is a plan for making full static mode in nuxt, you can track it here https://github.com/nuxt/rfcs/issues/22