javascript - 将 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
文件中移出,放到单独的函数中,这样它就不会那么混乱了。这不可能吗?
解决方案
导入时需要遵循两条规则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
. 如我错了请纠正我
推荐阅读
- c# - 如何在 Windows 10 IIS 中支持 Blazor Server 应用程序上的多个浏览器选项卡?
- javascript - 登录期间我的 req.body 一直未定义
- asp.net-web-api - Asp.Net Core Web API 补丁 ID 始终为 NULL
- python - 每隔一段时间的Python脚本读取终端
- python - 序列的第一个和最后一个索引
- c++ - 对“距离”的错误引用不明确
- amazon-web-services - AWS ACM 证书不涵盖已验证(子)域,仅 Lambda 域
- python - Kubernetes 客户端 python API 错误 401 - 未经授权
- java - Spring 没有在 Prototype Beans 中调用 @Autowired 设置器
- typescript - TypeScript 中有没有办法直接从对象的键创建新类型?