Ошибка при развертывании блога Gatsby в Netlify - PullRequest
0 голосов
/ 10 февраля 2020

Я развернул свой блог Gatsby на Netlify, но получил несколько проблем.

Issue - Когда я запускаю "gatsby development", я вижу сообщения в блоге, даже если есть сообщения об ошибках. - Однако когда я запускаю «gatsby build», ошибки перестают обрабатываться. - Я успешно развернул с удалением содержимого внутри "gatsby- node.js". - Я вижу развернутую веб-страницу, но сообщения блога, управляемые через Contentful, не работают. - Если я разверну содержимое с содержимым внутри "gatsby- node.js", оно не будет работать и не будет работать.

Наблюдение - Поскольку "gatsby- node.js" предназначено для пост-создания, это влияет на мои страницы блога. - Если я остаюсь как есть, он возвращает сообщение об ошибке, в котором говорится: «TypeError: Невозможно прочитать свойство 'replace' of undefined". - Поверьте, это не является содержательной проблемой, поскольку я могу видеть все сообщения через среду разработки.

Ожидаемый результат - Отображение сообщений на веб-странице.

Было бы признательно, если вы поделитесь своими мыслями / идеями для решения проблемы.

const config = require('./src/utils/siteConfig')
const path = require(`path`)

const { createFilePath } = require('gatsby-source-filesystem');

exports.onCreateNode = ({ node, boundActionCreators, getNode }) => {
	const { createNodeField } = boundActionCreators;

	if (node.internal.type === `MarkdownRemark`) {
		const value = createFilePath({ node, getNode });
		createNodeField({
			name: `slug`,
			node,
			value,
		});
	}
};

exports.createPages = ({ graphql, actions }) => {
  const { createPage } = actions

  const loadPosts = new Promise((resolve, reject) => {
    graphql(`
      {
        allContentfulPost(
          sort: { fields: [publishDate], order: DESC }
          limit: 10000
        ) {
          edges {
            node {
              slug
              publishDate
            }
          }
        }
      }
    `).then(result => {
      const posts = result.data.allContentfulPost.edges
      const postsPerFirstPage = config.postsPerHomePage
      const postsPerPage = config.postsPerPage
      const numPages = Math.ceil(
        posts.slice(postsPerFirstPage).length / postsPerPage
      )

      // Create main home page
      createPage({
        path: `/`,
        component: path.resolve(`./src/templates/index.js`),
        context: {
          limit: postsPerFirstPage,
          skip: 0,
          numPages: numPages + 1,
          currentPage: 1,
        },
      })

      // Create additional pagination on home page if needed
      Array.from({ length: numPages }).forEach((_, i) => {
        createPage({
          path: `/${i + 2}/`,
          component: path.resolve(`./src/templates/index.js`),
          context: {
            limit: postsPerPage,
            skip: i * postsPerPage + postsPerFirstPage,
            numPages: numPages + 1,
            currentPage: i + 2,
          },
        })
      })

      // Create each individual post
      posts.forEach((edge, i) => {
        const prev = i === 0 ? null : posts[i - 1].node
        const next = i === posts.length - 1 ? null : posts[i + 1].node
        createPage({
          path: `${edge.node.slug}/`,
          component: path.resolve(`./src/templates/post.js`),
          context: {
            slug: edge.node.slug,
            prev,
            next,
          },
        })
      })
      resolve()
    })
  })

  const loadTags = new Promise((resolve, reject) => {
    graphql(`
      {
        allContentfulTag {
          edges {
            node {
              slug
              post {
                id
              }
            }
          }
        }
      }
    `).then(result => {
      const tags = result.data.allContentfulTag.edges
      const postsPerPage = config.postsPerPage

      // Create tag pages with pagination if needed
      tags.map(({ node }) => {
        const totalPosts = node.post !== null ? node.post.length : 0
        const numPages = Math.ceil(totalPosts / postsPerPage)
        Array.from({ length: numPages }).forEach((_, i) => {
          createPage({
            path:
              i === 0 ? `/tag/${node.slug}/` : `/tag/${node.slug}/${i + 1}/`,
            component: path.resolve(`./src/templates/tag.js`),
            context: {
              slug: node.slug,
              limit: postsPerPage,
              skip: i * postsPerPage,
              numPages: numPages,
              currentPage: i + 1,
            },
          })
        })
      })
      resolve()
    })
  })


  const loadPages = new Promise((resolve, reject) => {
    graphql(`
      {
        allContentfulPage {
          edges {
            node {
              slug
            }
          }
        }
      }
    `).then(result => {
      const pages = result.data.allContentfulPage.edges
      pages.map(({ node }) => {
        createPage({
          path: `${node.slug}/`,
          component: path.resolve(`./src/templates/page.js`),
          context: {
            slug: node.slug,
          },
        })
      })
      resolve()
    })
  })


  
  return Promise.all([loadPosts, loadTags, loadPages])
}
error (node:91907) [DEP0066] DeprecationWarning: OutgoingMessage.prototype._headers is deprecated
Starting to fetch data from Contentful
Fetching default locale
default locale is : en-US
contentTypes fetched 4
Updated entries  11
Deleted entries  0
Updated assets  23
Deleted assets  0
Fetch Contentful data: 165.880ms
error gatsby-node.js returned an error


  TypeError: Cannot read property 'replace' of undefined

  - utils.js:71 slash
    [smy.jp]/[gatsby-source-filesystem]/utils.js:71:15

  - create-file-path.js:40 module.exports
    /[gatsby-source-filesystem]/create-file-path.js:40:61

  - gatsby-node.js:10 Object.exports.onCreateNode
    /gatsby-node.js:10:17

  - api-runner-node.js:225 runAPI
    /[gatsby]/dist/utils/api-runner-node.js:225:37

  - api-runner-node.js:348 Promise.catch.decorateEvent.pluginName
    /[gatsby]/dist/utils/api-runner-node.js:348:19

  - debuggability.js:313 Promise._execute
    /[bluebird]/js/release/debuggability.js:313:9

  - promise.js:483 Promise._resolveFromExecutor
    [smy.jp]/[bluebird]/js/release/promise.js:483:18

  - promise.js:79 new Promise
    /[bluebird]/js/release/promise.js:79:10

  - api-runner-node.js:347 
    [smy.jp]/[gatsby]/dist/utils/api-runner-node.js:347:16

  - util.js:16 tryCatcher
    /[bluebird]/js/release/util.js:16:23

  - reduce.js:155 Object.gotValue
    /[bluebird]/js/release/reduce.js:155:18

  - reduce.js:144 Object.gotAccum
    /[bluebird]/js/release/reduce.js:144:25

  - util.js:16 Object.tryCatcher
    /[bluebird]/js/release/util.js:16:23

  - promise.js:512 Promise._settlePromiseFromHandler
    /[bluebird]/js/release/promise.js:512:31

  - promise.js:569 Promise._settlePromise
    /[bluebird]/js/release/promise.js:569:18

  - promise.js:614 Promise._settlePromise0
    /[bluebird]/js/release/promise.js:614:10

  - promise.js:694 Promise._settlePromises
    /[bluebird]/js/release/promise.js:694:18

  - async.js:138 _drainQueueStep
    /[bluebird]/js/release/async.js:138:12

  - async.js:131 _drainQueue
    /[bluebird]/js/release/async.js:131:9

  - async.js:147 Async._drainQueues
    /[bluebird]/js/release/async.js:147:5

  - async.js:17 Immediate.Async.drainQueues [as _onImmediate]
    /[bluebird]/js/release/async.js:17:14

  - timers.js:439 processImmediate
    internal/timers.js:439:21

1 Ответ

0 голосов
/ 11 февраля 2020

Постороннему сложно отлаживать ваш код.

Я бы посоветовал исключить код:

  • Удалите весь код из gatsby- node.js
  • Добавьте код в gatsby-node.js и создавайте свой проект, пока не встретите твоя ошибка
  • Это отнимает много времени, но может быть необходимо. Тогда, по крайней мере, вы знаете, кто виноват.
  - utils.js:71 slash
    [smy.jp]/[gatsby-source-filesystem]/utils.js:71:15

  - create-file-path.js:40 module.exports
    /[gatsby-source-filesystem]/create-file-path.js:40:61

намекает на то, что что-то может быть не так с вашим gatsby-config.js. Дважды проверьте плагины gatsby-source-filesystem.

...