[英]Refactoring gatsby-node File into separate files not working
嘗試通過外包一些代碼來重構我的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
}
我的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 生命周期時拋出錯誤:
博客文章未定義
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
不會那么混亂了。 這不可能嗎?
在gatsby-node.js
導入時需要遵循兩條規則:
./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 語句的技巧。
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
之外的狀態。 如果我錯了糾正我
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.