@acto/gatsby-source-filesystem 中文文档教程
@acto/gatsby-source-filesystem
一个 Gatsby 源插件,用于将数据采购到您的 Gatsby 应用程序中 从您的本地文件系统。
该插件从文件创建 File
节点。 形形色色的“变形金刚” 插件可以将 File
节点转换为各种其他类型的数据,例如 gatsby-transformer-json
将 JSON 文件转换为 JSON 数据节点并 gatsby-transformer-remark
将 markdown 文件转换为 MarkdownRemark
您可以从中查询降价的 HTML 表示形式的节点。
Install
npm install --save gatsby-source-filesystem
How to use
// In your gatsby-config.js
module.exports = {
plugins: [
// You can have multiple instances of this plugin
// to read source nodes from different locations on your
// filesystem.
//
// The following sets up the Jekyll pattern of having a
// "pages" directory for Markdown files and a "data" directory
// for `.json`, `.yaml`, `.csv`.
{
resolve: `gatsby-source-filesystem`,
options: {
name: `pages`,
path: `${__dirname}/src/pages/`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `data`,
path: `${__dirname}/src/data/`,
ignore: [`**/\.*`], // ignore files starting with a dot
},
},
],
}
Options
除了名称和路径参数之外,您还可以传递可选的 ignore
文件 glob 数组以忽略。
它们将被添加到以下默认列表中:
**/*.un~
**/.DS_Store
**/.gitignore
**/.npmignore
**/.babelrc
**/yarn.lock
**/node_modules
../**/dist/**
How to query
您可以像下面这样查询文件节点:
{
allFile {
edges {
node {
extension
dir
modifiedTime
}
}
}
}
要按您在配置中指定的 name
进行过滤,请使用 sourceInstanceName
:
{
allFile(filter: { sourceInstanceName: { eq: "data" } }) {
edges {
node {
extension
dir
modifiedTime
}
}
}
}
Helper functions
gatsby-source-filesystem
导出两个辅助函数:
createFilePath
createRemoteFileNode
createFilePath
当从文件构建页面时,您通常希望从文件系统上的文件路径创建 URL。 例如,如果你在 src/content/2018-01-23-an-exploration-of-the-nature-of-reality/index.md
有一个降价文件,你可能想把它变成您网站上的页面 example.com/2018-01-23-an-exploration-of-the-nature-of-reality/
。 createFilePath
是一个帮助函数,可以让这个任务变得更容易。
createFilePath({
// The node you'd like to convert to a path
// e.g. from a markdown, JSON, YAML file, etc
node:
// Method used to get a node
// The parameter from `onCreateNode` should be passed in here
getNode:
// The base path for your files.
// Defaults to `src/pages`. For the example above, you'd use `src/content`.
basePath:
// Whether you want your file paths to contain a trailing `/` slash
// Defaults to true
trailingSlash:
})
Example usage
以下内容摘自 Gatsby 教程,第七部分,用于为降价页面创建 URL slugs。
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
// Ensures we are processing only markdown files
if (node.internal.type === "MarkdownRemark") {
// Use `createFilePath` to turn markdown files in our `data/faqs` directory into `/faqs/slug`
const relativeFilePath = createFilePath({
node,
getNode,
basePath: "data/faqs/",
})
// Creates new query'able field with name of 'slug'
createNodeField({
node,
name: "slug",
value: `/faqs${relativeFilePath}`,
})
}
}
createRemoteFileNode
在为远程数据源(例如无头 CMS)构建源插件时,它们的数据通常会链接到远程存储的文件,这些文件通常便于下载,因此您可以在本地使用它们。
createRemoteFileNode
帮助程序可以轻松下载远程文件并将它们添加到站点的 GraphQL 架构中。
createRemoteFileNode({
// The source url of the remote file
url: `https://example.com/a-file.jpg`,
// The id of the parent node (i.e. the node to which the new remote File node will be linked to.
parentNodeId,
// The redux store which is passed to all Node APIs.
store,
// Gatsby's cache which the helper uses to check if the file has been downloaded already. It's passed to all Node APIs.
cache,
// The action used to create nodes
createNode,
// A helper function for creating node Ids
createNodeId,
// OPTIONAL
// Adds htaccess authentication to the download request if passed in.
auth: { htaccess_user: `USER`, htaccess_pass: `PASSWORD` },
// OPTIONAL
// Sets the file extension
ext: ".jpg",
})
Example usage
以下示例摘自 gatsby-source-wordpress。 下载的文件创建为 File
节点,然后链接到 WordPress Media 节点,因此它既可以作为常规 File
节点查询,也可以从 localFile 字段。
const { createRemoteFileNode } = require(`gatsby-source-filesystem`)
exports.downloadMediaFiles = ({
nodes,
store,
cache,
createNode,
createNodeId,
_auth,
}) => {
nodes.map(async node => {
let fileNode
// Ensures we are only processing Media Files
// `wordpress__wp_media` is the media file type name for Wordpress
if (node.__type === `wordpress__wp_media`) {
try {
fileNode = await createRemoteFileNode({
url: node.source_url,
parentNodeId: node.id,
store,
cache,
createNode,
createNodeId,
auth: _auth,
})
} catch (e) {
// Ignore
}
}
// Adds a field `localFile` to the node
// ___NODE appendix tells Gatsby that this field will link to another node
if (fileNode) {
node.localFile___NODE = fileNode.id
}
})
}
然后可以使用 GraphQL 查询文件节点。 请参阅 gatsby-source-wordpress 自述文件 中的示例,其中使用 gatsby-transformer-sharp 在组件 gatsby-image 中使用。
Retrieving the remote file name and extension
助手首先尝试通过解析 url 和提供的路径来检索文件名和扩展名(例如,如果 url 是 https://example.com/image.jpg,扩展名将被推断为 .jpg 和名称为
image
)。 如果 url 不包含扩展名,我们使用 file-type
包来推断文件类型。 最后,名称和扩展名可以 显式传递,如下所示:
createRemoteFileNode({
// The source url of the remote file
url: `https://example.com/a-file-without-an-extension`,
parentNodeId: node.id,
store,
cache,
createNode,
createNodeId,
// if necessary!
ext: ".jpg",
name: "image",
})
@acto/gatsby-source-filesystem
A Gatsby source plugin for sourcing data into your Gatsby application from your local filesystem.
The plugin creates File
nodes from files. The various "transformer" plugins can transform File
nodes into various other types of data e.g. gatsby-transformer-json
transforms JSON files into JSON data nodes and gatsby-transformer-remark
transforms markdown files into MarkdownRemark
nodes from which you can query an HTML representation of the markdown.
Install
npm install --save gatsby-source-filesystem
How to use
// In your gatsby-config.js
module.exports = {
plugins: [
// You can have multiple instances of this plugin
// to read source nodes from different locations on your
// filesystem.
//
// The following sets up the Jekyll pattern of having a
// "pages" directory for Markdown files and a "data" directory
// for `.json`, `.yaml`, `.csv`.
{
resolve: `gatsby-source-filesystem`,
options: {
name: `pages`,
path: `${__dirname}/src/pages/`,
},
},
{
resolve: `gatsby-source-filesystem`,
options: {
name: `data`,
path: `${__dirname}/src/data/`,
ignore: [`**/\.*`], // ignore files starting with a dot
},
},
],
}
Options
In addition to the name and path parameters you may pass an optional ignore
array of file globs to ignore.
They will be added to the following default list:
**/*.un~
**/.DS_Store
**/.gitignore
**/.npmignore
**/.babelrc
**/yarn.lock
**/node_modules
../**/dist/**
How to query
You can query file nodes like the following:
{
allFile {
edges {
node {
extension
dir
modifiedTime
}
}
}
}
To filter by the name
you specified in the config, use sourceInstanceName
:
{
allFile(filter: { sourceInstanceName: { eq: "data" } }) {
edges {
node {
extension
dir
modifiedTime
}
}
}
}
Helper functions
gatsby-source-filesystem
exports two helper functions:
createFilePath
createRemoteFileNode
createFilePath
When building pages from files, you often want to create a URL from a file's path on the file system. E.g. if you have a markdown file at src/content/2018-01-23-an-exploration-of-the-nature-of-reality/index.md
, you might want to turn that into a page on your site at example.com/2018-01-23-an-exploration-of-the-nature-of-reality/
. createFilePath
is a helper function to make this task easier.
createFilePath({
// The node you'd like to convert to a path
// e.g. from a markdown, JSON, YAML file, etc
node:
// Method used to get a node
// The parameter from `onCreateNode` should be passed in here
getNode:
// The base path for your files.
// Defaults to `src/pages`. For the example above, you'd use `src/content`.
basePath:
// Whether you want your file paths to contain a trailing `/` slash
// Defaults to true
trailingSlash:
})
Example usage
The following is taken from Gatsby Tutorial, Part Seven and is used to create URL slugs for markdown pages.
const { createFilePath } = require(`gatsby-source-filesystem`)
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
// Ensures we are processing only markdown files
if (node.internal.type === "MarkdownRemark") {
// Use `createFilePath` to turn markdown files in our `data/faqs` directory into `/faqs/slug`
const relativeFilePath = createFilePath({
node,
getNode,
basePath: "data/faqs/",
})
// Creates new query'able field with name of 'slug'
createNodeField({
node,
name: "slug",
value: `/faqs${relativeFilePath}`,
})
}
}
createRemoteFileNode
When building source plugins for remote data sources such as headless CMSs, their data will often link to files stored remotely that are often convenient to download so you can work with them locally.
The createRemoteFileNode
helper makes it easy to download remote files and add them to your site's GraphQL schema.
createRemoteFileNode({
// The source url of the remote file
url: `https://example.com/a-file.jpg`,
// The id of the parent node (i.e. the node to which the new remote File node will be linked to.
parentNodeId,
// The redux store which is passed to all Node APIs.
store,
// Gatsby's cache which the helper uses to check if the file has been downloaded already. It's passed to all Node APIs.
cache,
// The action used to create nodes
createNode,
// A helper function for creating node Ids
createNodeId,
// OPTIONAL
// Adds htaccess authentication to the download request if passed in.
auth: { htaccess_user: `USER`, htaccess_pass: `PASSWORD` },
// OPTIONAL
// Sets the file extension
ext: ".jpg",
})
Example usage
The following example is pulled from gatsby-source-wordpress. Downloaded files are created as File
nodes and then linked to the WordPress Media node, so it can be queried both as a regular File
node and from the localFile
field in the Media node.
const { createRemoteFileNode } = require(`gatsby-source-filesystem`)
exports.downloadMediaFiles = ({
nodes,
store,
cache,
createNode,
createNodeId,
_auth,
}) => {
nodes.map(async node => {
let fileNode
// Ensures we are only processing Media Files
// `wordpress__wp_media` is the media file type name for Wordpress
if (node.__type === `wordpress__wp_media`) {
try {
fileNode = await createRemoteFileNode({
url: node.source_url,
parentNodeId: node.id,
store,
cache,
createNode,
createNodeId,
auth: _auth,
})
} catch (e) {
// Ignore
}
}
// Adds a field `localFile` to the node
// ___NODE appendix tells Gatsby that this field will link to another node
if (fileNode) {
node.localFile___NODE = fileNode.id
}
})
}
The file node can then be queried using GraphQL. See an example of this in the gatsby-source-wordpress README where downloaded images are queried using gatsby-transformer-sharp to use in the component gatsby-image.
Retrieving the remote file name and extension
The helper tries first to retrieve the file name and extension by parsing the url and the path provided (e.g. if the url is https://example.com/image.jpg, the extension will be inferred as .jpg
and the name as image
). If the url does not contain an extension, we use the file-type
package to infer the file type. Finally, the name and the extension can be explicitly passed, like so:
createRemoteFileNode({
// The source url of the remote file
url: `https://example.com/a-file-without-an-extension`,
parentNodeId: node.id,
store,
cache,
createNode,
createNodeId,
// if necessary!
ext: ".jpg",
name: "image",
})