首页 > 解决方案 > 将 gatsby-node 文件重构为单独的文件不起作用

问题描述

尝试gatsby-node通过外包一些代码来重构我的文件。现在试图在我的gatsby-node

const createBlogPostPages = require("./gatsby-utils/createBlogPostPages");

exports.createPages = async ({ actions, graphql, reporter }) => {
  //...some code
  await createBlogPostPages({ actions, graphql, reporter });
  //...some code
}

和 my createBlogPostPages,它在不同的文件中,看起来像这样:

const path = require("path");

module.exports = async function({ actions, graphql, reporter }) {
  const { createPage } = actions;

  const blogArticles = await graphql(`
    {
      allMdx(filter: { fileAbsolutePath: { regex: "/content/blog/.*/" } }) {
        edges {
          node {
            id
            fileAbsolutePath
            fields {
              slug
            }
            frontmatter {
              title
              tags
              date
              tagline
            }
          }
        }
      }
    }
  `);

  blogArticles.data.allMdx.edges.forEach(({ node }) => {
    let imageFileName = ... //some stuff

    createPage({
      path: `${node.fields.slug}`,
      component: path.resolve(`./src/templates/blog-post.js`),
      context: {
        slug: `${node.fields.slug}`,
        id: node.id,
        imageFileName: imageFileName
      }
    });
  });
};

当它直接在gatsby-node. 但是,移动了东西后,我现在得到:

“gatsby-node.js”在运行 createPages 生命周期时抛出错误:

blogArticles 未定义

ReferenceError:未定义 blogArticles

  • gatsby-node.js:177 Object.exports.createPages /Users/kohlisch/blogproject/gatsby-node.js:177:19

  • next_tick.js:68 process._tickCallback internal/process/next_tick.js:68:7

所以看起来它没有等待graphql查询解决?或者这可能是什么?我基本上只是想将一些东西从我的gatsby-node文件中移出,放到单独的函数中,这样它就不会那么混乱了。这不可能吗?

标签: javascriptnode.jsgatsbygraphql-js

解决方案


导入时需要遵循两条规则gatsby-node.js

1. 使用 node.js 的 require 语法。

./src/components/util/gatsby-node-functions

const importedFunction = () => {
  return Date.now();
};

module.exports.importedFunction = importedFunction;

gatsby-node.js

const { importedFunction } = require(`./src/components/util/gatsby-node-functions`);

// ...
// Use your imported functions
console.log(importedFunction());

参考:Gatsby repo issue,如果你想增加复杂性只是为了使用 import 语句,还包括如何使用 ES6 import 语句。

2.不要将gatsby-node.js特定属性传递给您导入的函数

例如,如果您尝试外包 createPages 函数,则操作将未定义:

const importedFunction = (actions, node) => {
    const {createPage} = actions; // actions is undefined
    createPage({
      path: `${node.fields.slug}`,
      component: path.resolve(`./src/templates/blog-post.js`),
      context: {
        slug: `${node.fields.slug}`,
        id: node.id,
      }
    });
};

module.exports.importedFunction = importedFunction;

随意推测为什么你不能传递属性。Gatsby 文档提到了用于处理状态的“Redux” 。也许 Redux 不提供你的gatsby-node.js. 如我错了请纠正我


推荐阅读