我试图建立一个盖茨比主题,使用gatsby-source-filesystem
源图像。
我已经为开发设置了一个yarn工作区,我的文件夹结构看起来像这样。
workspace/
├─ example.com/
│ ├─ src/
│ │ ├─ pages/
│ │ │ ├─ test.js
│ ├─ gatsby-config.js
│ ├─ package.json
├─ gatsby-theme-example/
│ ├─ src/
│ ├─ images/
│ ├─ gatsby-config.js
│ ├─ gatsby-node.js
│ ├─ package.json
yarn工作空间也正确设置,并且gatsby-theme-example
是它的依赖项。yarn workspaces info
正确地显示了workspaceDependencies
。
两个工作区都有一个gatsby-config.js
文件,gatsby-theme-example
中有gatsby-source-filesystem
文件。
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: path.join(__dirname, "images"),
},
},
我面临的问题是,我必须把图像在主题目录图像文件夹内,否则它们不会被gatsby-source-filesystem
找到。通过观看本视频和阅读教程,使用path.join
和__dirname
变量应该指向将主题作为依赖项安装的包,在我的例子中是example.com
奇怪的是,gatsby-theme-example/gatsby-config.js
中的gatsby-plugin-page-creator
插件完美地创建了example.com/src/pages
(网站目录)中定义的页面。
{
resolve: "gatsby-plugin-page-creator",
options: {
path: path.join(__dirname, "src/pages"),
},
},
我还在gatsby-theme-example/gatsby-node.js
中定义了onPreBootstrap
,像这样
exports.onPreBootstrap = ({ reporter }) => {
const contentPath = `${__dirname}/images/`
if (!fs.existsSync(contentPath)) {
reporter.info(`creating the ${contentPath} directory`)
fs.mkdirSync(contentPath)
}
}
在gatsby-theme-example
而不是example.com
中创建images目录
我使用gatsby@4.18.0
和gatsby-source-filesystem@4.18.0
,并使用以下命令启动项目:yarn workspace example.com start
我已经建立了一个repo,你可以用它来重现这个问题,像这样:
git clone https://github.com/AlexanderProd/gatsby-source-filesystem-theme-bug
yarn workspace example.com install
yarn workspace example.com start
- 转到http://localhost:8000/___graphql
- 运行以下查询
query MyQuery {
allFile {
edges {
node {
id
name
}
}
}
}
不确定是否应该这样做,但我找到了一个解决方案。
在指定主题的站点gatsby-config.js
(example.com/gatsby-config.js
)中,我添加了一个图像路径选项。
{
resolve: `gatsby-theme-example`,
options: {
imagesPath: path.join(__dirname, "images"),
},
},
,然后在主题gatsby-config.js
我使用的选项值。
module.exports = options => ({
plugins: [
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: options.imagesPath,
},
},
]
})
另一个解决方案,在这种情况下,最优的解决方案是仅使用images
作为路径。
{
resolve: `gatsby-source-filesystem`,
options: {
name: `images`,
path: `images`,
},
},
基于这个答案。