将 gatsby-node 文件重构为单独的文件不起作用

R. *_*sch 7 javascript node.js graphql-js gatsby

尝试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
}
Run Code Online (Sandbox Code Playgroud)

mycreateBlogPostPages位于不同的文件中,如下所示:

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
      }
    });
  });
};
Run Code Online (Sandbox Code Playgroud)

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

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

blogArticles 未定义

ReferenceError:博客文章未定义

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

  • next_tick.js:68 process._tickCallback 内部/process/next_tick.js:68:7

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

Eli*_*ant 4

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

1.使用node.js require语法。

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

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

module.exports.importedFunction = importedFunction;
Run Code Online (Sandbox Code Playgroud)

gatsby-node.js

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

// ...
// Use your imported functions
console.log(importedFunction());
Run Code Online (Sandbox Code Playgroud)

参考:Gatsby repo Issue,还包括如何使用 ES6 import 语句的 hack,如果你想增加使用 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;
Run Code Online (Sandbox Code Playgroud)

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