Movatterモバイル変換


[0]ホーム

URL:


Migrate to Netlify Today

Netlify announces the next evolution of Gatsby Cloud.Learn more

SupportLog In

Gatsby usesRedux internally to manage state. When you implement a Gatsby API, you are passed a collection of actions (equivalent to actions bound withbindActionCreators in Redux) which you can use to manipulate state on your site.

The objectactions contains the functions and these can be individually extracted by using ES6 object destructuring.

Start building today on Netlify!

Functions

Source

Declares URL Pattern that should be allowed to be used for Image or File CDN to prevent using of unexpected RemoteFile URLs.

Parameters

  • urlstring |string[]

    URLPattern or Array of URL Patternss that should be allowed.URLPattern is a string that can contain wildcards (*) or parameter placeholders (e.g. :id).

  • pluginIGatsbyPlugin
  • traceIdstring

Return value

IAddImageCdnAllowedUrl

Example

exports.onPreInit=({ actions})=>{  actions.addRemoteFileAllowedUrl(`https://your-wordpress-instance.com/*`)}

Source

Add a third-party schema to be merged into main schema. Schema has to be agraphql-js GraphQLSchema object.

This schema is going to be merged as-is. Merging it in this way willeasily break the main Gatsby Schema. Since we do not want that, thereforeit is the user’s responsibility to make sure that it does not happen.One such way of avoiding it is by namespacing the schema.

Parameters

  • destructured object
    • schemaGraphQLSchema

      GraphQL schema to add

  • pluginIGatsbyPlugin
  • traceIdstring

Return value

IAddThirdPartySchema

Source

Add a field extension to the GraphQL schema.

Extensions allow defining custom behavior which can be added to fieldsvia directive (in SDL) or on theextensions prop (with Type Builders).

The extension definition takes aname, anextend function, and optionalextensionargs for options. Theextend function has to return a (partial)field config, and receives the extension options and the previous field configas arguments.

Parameters

  • extensionGraphQLFieldExtensionDefinition

    The field extension definition

  • pluginIGatsbyPlugin
  • traceIdstring

Return value

ThunkAction<>

Example

exports.createSchemaCustomization=({ actions})=>{const{ createFieldExtension}= actionscreateFieldExtension({name:'motivate',args:{caffeine:'Int'},extend(options, prevFieldConfig){return{type:'String',args:{sunshine:{type:'Int',defaultValue:0,},},resolve(source, args, context, info){const motivation=(options.caffeine||0)- args.sunshineif(motivation>5)return'Work! Work! Work!'return'Maybe tomorrow.'},}},})}

Source

DEPRECATED. Use createJobV2 instead.

Create a “job”. This is a long-running process that is generallystarted as a side-effect to a GraphQL query.gatsby-plugin-sharp uses this forexample.

Gatsby doesn’t finish its process until all jobs are ended.

Use “createJobV2” instead

Parameters

  • jobObject

    A job object with at least an id set

    • idid

      The id of the job

  • plugin

Example

createJob({id:`write file id: 123`,fileName:`something.jpeg`})

Source

Create a “job”. This is a long-running process that is generallystarted as a side-effect to a GraphQL query.gatsby-plugin-sharp uses this forexample.

Gatsby doesn’t finish its process until all jobs are ended.

Parameters

  • jobObject

    A job object with name, inputPaths, outputDir and args

    • namestring

      The name of the job you want to execute

    • inputPathsstring[]

      The inputPaths that are needed to run

    • outputDirstring

      The directory where all files are being saved to

    • argsObject

      The arguments the job needs to execute

  • pluginPlugin

Return value

Promise<object>

Promise to see if the job is done executing

Example

createJobV2({name:`IMAGE_PROCESSING`,inputPaths:[`something.jpeg`],outputDir:`public/static`,args:{width:100,height:100}})

Source

Create a new node.

Parameters

  • nodeObject

    a node object

    • idstring

      The node’s ID. Must be globally unique.

    • parentstring

      The ID of the parent’s node. If the node isderived from another node, set that node as the parent. Otherwise it canjust benull.

    • childrenArray

      An array of children node IDs. If you’recreating the children nodes while creating the parent node, add thechildren node IDs here directly. If you’re adding a child node to aparent node created by a plugin, you can’t mutate this value directlyto add your node id, instead use the action creatorcreateParentChildLink.

    • internalObject

      node fields that aren’t generallyinteresting to consumers of node data but are very useful for plugin writersand Gatsby core. Only fields described below are allowed ininternal object.Using any type of custom fields will result in validation errors.

      • mediaTypestring

        An optional field to indicate totransformer plugins that your node has raw content they can transform.Use either an official media type (we use mime-db as our source(https://www.npmjs.com/package/mime-db) or a made-up one if your datadoesn’t fit in any existing bucket. Transformer plugins use node media typesfor deciding if they should transform a node into a new one. E.g.markdown transformers look for media types oftext/markdown.

      • typestring

        An arbitrary globally unique typechosen by the plugin creating the node. Should be descriptive of thenode as the type is used in forming GraphQL types so users will queryfor nodes based on the type chosen here. Nodes of a given type canonly be created by one plugin.

      • contentstring

        An optional field. This is rarelyused. It is used when a source plugin sources data it doesn’t know howto transform e.g. a markdown string pulled from an API. The source plugincan defer the transformation to a specialized transformer plugin likegatsby-transformer-remark. Thiscontent field holds the raw content(so for the markdown case, the markdown string).

        Data that’s already structured should be added to the top-level of the nodeobject andnot added here. You should notJSON.stringify your node’sdata here.

        If the content is very large and can be lazy-loaded, e.g. a file on disk,you can define aloadNodeContent function for this node and the nodecontent will be lazy loaded when it’s needed.

      • contentDigeststring

        the digest for the contentof this node. Helps Gatsby avoid doing extra work on data that hasn’tchanged.

      • descriptionstring

        An optional field. Humanreadable description of what this node represent / its source. It willbe displayed when type conflicts are found, making it easier to findand correct type conflicts.

      • contentFilePathstring

        An optional field. A plugincan add an absolute path to a content file (e.g. markdown file) herewhile creating the node. Example: gatsby-plugin-mdx adds the absolute pathof theFile node to theMdx node underinternal.contentFilePath.

  • pluginPlugin
  • actionOptionsActionOptions

Return value

Promise

The returned Promise resolves when all cascadingonCreateNode API calls triggered bycreateNode have finished.

Example

createNode({// Data for the node.field1:`a string`,field2:10,field3:true,...arbitraryOtherData,// Required fields.id:`a-node-id`,parent:`the-id-of-the-parent-node`,// or null if it's a source node without a parentchildren:[],internal:{type:`CoolServiceMarkdownField`,contentDigest: crypto.createHash(`md5`).update(JSON.stringify(fieldData)).digest(`hex`),mediaType:`text/markdown`,// optionalcontent:JSON.stringify(fieldData),// optionaldescription:`Cool Service: "Title of entry"`,// optional}})

Source

Extend another node. The new node field is placed under thefieldskey on the extended node object.

Once a plugin has claimed a field name the field name can’t be used byother plugins. Also since nodes are immutable, you can’t mutate the nodedirectly. So to extend another node, use this.

Parameters

  • destructured object
    • nodeObject

      the target node object

    • namestring

      the name for the field

    • valueany

      the value for the field

  • pluginPlugin
  • actionOptionsActionOptions

Example

createNodeField({  node,name:`happiness`,value:`is sweet graphql queries`})// The field value is now accessible at node.fields.happiness

Source

Create a page. Seethe guide on creating and modifying pagesfor detailed documentation about creating pages.

Parameters

  • pageObject

    a page object

    • pathstring

      Any valid URL. Must start with a forward slash. Unicode characters should be passed directly and not encoded (eg.á not%C3%A1).

    • matchPathstring

      Path that Reach Router uses to match the page on the client side.Also see docs onmatchPath

    • ownerNodeIdstring

      The id of the node that owns this page. This is used for routing users to previews via the unstable_createNodeManifest public action. Since multiple nodes can be queried on a single page, this allows the user to tell us which node is the main node for the page. Note that the ownerNodeId must be for a node which is queried on this page via a GraphQL query.

    • componentstring

      The absolute path to the component for this page

    • contextObject

      Context data for this page. Passed as propsto the componentthis.props.pageContext as well as to the graphql queryas graphql arguments.

    • slicesObject

      A mapping of alias-of-id for Slices rendered on this page. See the technical docs for theGatsby Slice API.

    • deferboolean

      When set totrue, Gatsby will exclude the page from the build step and instead generate it during the first HTTP request. Default value isfalse. Also see docs onDeferred Static Generation.

  • pluginPlugin
  • actionOptionsActionOptions

Example

createPage({path:`/my-sweet-new-page/`,component: path.resolve(`./src/templates/my-sweet-new-page.js`),ownerNodeId:`123456`,// The context is passed as props to the component as well// as into the component's GraphQL query.context:{id:`123456`,},})

Source

Creates a link between a parent and child node. This is used when youtransform content from a node creating a new child node. You need to addthis new child node to thechildren array of the parent but since youdon’t have direct access to the immutable parent node, use this actioninstead.

Parameters

  • destructured object
    • parentObject

      the parent node object

    • childObject

      the child node object

  • pluginPlugin

Example

createParentChildLink({parent: parentNode,child: childNode})

Source

Create a redirect from one page to another.

Redirects must be implemented by your deployment platform (e.g. Gatsby Cloud, Netlify, etc.). You can use anadapter or plugins for this. Alternatively, you can usegatsby-plugin-meta-redirect to generate meta redirect HTML files for redirecting on any static file host.

You can read the source code ofgatsby-adapter-netlify to see how redirects are implemented on Netlify. Redirects also work out of the box on Gatsby Cloud.

Keep the redirects configuration in sync with trailing slash configuration fromGatsby Config API.

Parameters

  • redirectObject

    Redirect data

    • fromPathstring

      Any valid URL. Must start with a forward slash

    • isPermanentboolean

      This is a permanent redirect; defaults to temporary

    • redirectInBrowserboolean

      Redirects are generally for redirecting legacy URLs to their new configuration on the server. If you can’t update your UI for some reason, setredirectInBrowser to true and Gatsby will handle redirecting in the client as well. You almost never need this so be sure your use case fits before enabling.

    • toPathstring

      URL of a created page (seecreatePage)

    • ignoreCaseboolean

      (Plugin-specific) Ignore case when looking for redirects

    • forceboolean

      (Plugin-specific) Will trigger the redirect even if thefromPath matches a piece of content. This is not part of the Gatsby API, but implemented by (some) plugins that configure hosting provider redirects

    • statusCodenumber

      (Plugin-specific) Manually set the HTTP status code. This allows you to create a rewrite (status code 200) or custom error page (status code 404). Note that this will override theisPermanent option which also sets the status code. This is not part of the Gatsby API, but implemented by (some) plugins that configure hosting provider redirects

    • conditionsObject

      Specify a country or language based redirect

      • countrystring |string[]

        A two-letter country code based on the regional indicator symbol

      • languagestring |string[]

        A two-letter identifier defined by ISO 639-1

    • rest

Example

// Generally you create redirects while creating pages.exports.createPages=({ graphql, actions})=>{const{ createRedirect}= actionscreateRedirect({fromPath:'/old-url/',toPath:'/new-url/',isPermanent:true})createRedirect({fromPath:'/url/',toPath:'/zn-CH/url/',conditions:{language:'zn'}})createRedirect({fromPath:'/url/',toPath:'/en/url/',conditions:{language:['ca','us']}})createRedirect({fromPath:'/url/',toPath:'/ca/url/',conditions:{country:'ca'}})createRedirect({fromPath:'/url/',toPath:'/en/url/',conditions:{country:['ca','us']}})createRedirect({fromPath:'/not_so-pretty_url/',toPath:'/pretty/url/',statusCode:200})// Create pages here}

Source

Only available in:createSchemaCustomization

Make functionality available on field resolvercontext

Parameters

  • contextobject

    Object to make available oncontext.When called from a plugin, the context value will be namespaced underthe camel-cased plugin name without the “gatsby-” prefix

  • pluginIGatsbyPlugin
  • traceIdstring

Return value

ThunkAction<>

Example

constgetHtml=md=>remark().use(html).process(md)exports.createSchemaCustomization=({ actions})=>{  actions.createResolverContext({ getHtml})}// The context value can then be accessed in any field resolver like this:exports.createSchemaCustomization=({ actions, schema})=>{  actions.createTypes(schema.buildObjectType({name:'Test',interfaces:['Node'],fields:{md:{type:'String!',asyncresolve(source, args, context, info){const processed=await context.transformerRemark.getHtml(source.internal.contents)return processed.contents}}}}))}

Source

Record that a page was visited on the server..

Parameters

  • chunkNamestring
  • destructured object
    • idstring

      the chunkName for the page component.


Source

Only available in:createPages

Create a new Slice. See the technical docs for theGatsby Slice API.

Parameters

  • payloadICreateSliceInput
  • pluginIGatsbyPlugin
  • traceIdstring
  • destructured object
  • sliceObject

    a slice object

    • idstring

      The unique ID for this slice

    • componentstring

      The absolute path to the component for this slice

    • contextObject

      Context data for this slice. Passed as propsto the componentthis.props.sliceContext as well as to the graphql queryas graphql arguments.

Return value

ICreateSliceAction

Example

exports.createPages=({ actions})=>{  actions.createSlice({id:`navigation-bar`,component: path.resolve(`./src/components/navigation-bar.js`),})}

Source

Add type definitions to the GraphQL schema.

Parameters

  • typesstring |GraphQLOutputType |GatsbyGraphQLType |string[] |GraphQLOutputType[] |GatsbyGraphQLType[]

    Type definitions

    Type definitions can be provided either asgraphql-js types, inGraphQL schema definition language (SDL)or using Gatsby Type Builders available on theschema API argument.

    Things to note:

    • type definitions targeting node types, i.e.MarkdownRemark and othersadded insourceNodes oronCreateNode APIs, need to implement theNode interface. Interface fields will be added automatically, but itis mandatory to label those types withimplements Node.
    • by default, explicit type definitions fromcreateTypes will be mergedwith inferred field types, and default field resolvers forDate (whichadds formatting options) andFile (which resolves the field value asarelativePath foreign-key field) are added. This behavior can becustomised with@infer,@dontInfer directives or extensions. Fieldsmay be assigned resolver (and other option like args) with additionaldirectives. Currently@dateformat,@link,@fileByRelativePath and@proxy are available.

    Schema customization controls:

    • @infer - run inference on the type and add fields that don’t exist on the

    defined type to it.

    • @dontInfer - don’t run any inference on the type

    Extensions to add resolver options:

    • @dateformat - add date formatting arguments. AcceptsformatString andlocale options that sets the defaults for this field
    • @link - connect to a different Node. Argumentsby andfrom, whichdefine which field to compare to on a remote node and which field to use onthe source node
    • @fileByRelativePath - connect to a File node. Same arguments. Thedifference from link is that this normalizes the relative path to berelative from the path where source node is found.
    • @proxy - in case the underlying node data contains field names withcharacters that are invalid in GraphQL,proxy allows to explicitlyproxy those properties to fields with valid field names. Takes afrom arg.
  • pluginIGatsbyPlugin
  • traceIdstring

Return value

ICreateTypes

Example

exports.createSchemaCustomization=({ actions})=>{const{ createTypes}= actionsconst typeDefs=`    """    Markdown Node    """    type MarkdownRemark implements Node @infer {      frontmatter: Frontmatter!    }    """    Markdown Frontmatter    """    type Frontmatter @infer {      title: String!      author: AuthorJson! @link      date: Date! @dateformat      published: Boolean!      tags: [String!]!    }    """    Author information    """    # Does not include automatically inferred fields    type AuthorJson implements Node @dontInfer {      name: String!      birthday: Date! @dateformat(locale: "ru")    }`createTypes(typeDefs)}// using Gatsby Type Builder APIexports.createSchemaCustomization=({ actions, schema})=>{const{ createTypes}= actionsconst typeDefs=[    schema.buildObjectType({name:'MarkdownRemark',fields:{frontmatter:'Frontmatter!'},interfaces:['Node'],extensions:{infer:true,},}),    schema.buildObjectType({name:'Frontmatter',fields:{title:{type:'String!',resolve(parent){return parent.title||'(Untitled)'}},author:{type:'AuthorJson'extensions:{link:{},},}date:{type:'Date!'extensions:{dateformat:{},},},published:'Boolean!',tags:'[String!]!',}}),    schema.buildObjectType({name:'AuthorJson',fields:{name:'String!'birthday:{type:'Date!'extensions:{dateformat:{locale:'ru',},},},},interfaces:['Node'],extensions:{infer:false,},}),]createTypes(typeDefs)}

Source

Delete a node

Parameters

  • nodeobject

    A node object. See the “createNode” action for more information about the node object details.

  • pluginPlugin

Example

deleteNode(node)

Source

Delete a page

Parameters

  • pageObject

    a page object

    • pathstring

      The path of the page

    • componentstring

      The absolute path to the page component

Example

deletePage(page)

Source

Marks a source plugin as “stateful” which disables automatically deleting untouched nodes. Stateful source plugins manage deleting their own nodes without stale node checks in Gatsby.Enabling this is a major performance improvement for source plugins that manage their own node deletion. It also lowers the total memory required by a source plugin.When using this action, check if it’s supported first withhasFeature('stateful-source-nodes'),hasFeature is exported fromgatsby-plugin-utils.

Parameters

  • pluginPlugin
  • destructured object

Example

import{ hasFeature}from"gatsby-plugin-utils"exports.sourceNodes=({ actions})=>{if(hasFeature(`stateful-source-nodes`)){     actions.enableStatefulSourceNodes()}else{// fallback to old behavior where all nodes are iterated on and touchNode is called.}}

Source

DEPRECATED. Use createJobV2 instead.

End a “job”.

Gatsby doesn’t finish its process until all jobs are ended.

Use “createJobV2” instead

Parameters

  • jobObject

    A job object with at least an id set

    • idid

      The id of the job

  • plugin

Example

endJob({id:`write file id: 123`})

Source

Only available in:createSchemaCustomization

Write GraphQL schema to file

Writes out inferred and explicitly specified type definitions. This is notthe full GraphQL schema, but only the types necessary to recreate all typedefinitions, i.e. it does not include directives, built-ins, and derivedtypes for filtering, sorting, pagination etc. Optionally, you can define alist of types to include/exclude. This is recommended to avoid includingdefinitions for plugin-created types.

The first object parameter is required, however all the fields in the object are optional.

Parameters

  • destructured object
    • pathstring

      The path to the output file, defaults toschema.gql

    • includeobject

      Configure types to include

      • typesstring[]

        Only include these types

      • pluginsstring[]

        Only include types owned by these plugins

    • excludeobject

      Configure types to exclude

      • typesstring[]

        Do not include these types

      • pluginsstring[]

        Do not include types owned by these plugins

    • withFieldTypesboolean

      Include field types, defaults totrue

  • pluginIGatsbyPlugin
  • traceIdstring

Return value

IPrintTypeDefinitions

Example

exports.createSchemaCustomization=({ actions})=>{// This code writes a GraphQL schema to a file named `schema.gql`.  actions.printTypeDefinitions({})}
exports.createSchemaCustomization=({ actions})=>{// This code writes a GraphQL schema to a file named `schema.gql`, but this time it does not include field types.  actions.printTypeDefinitions({withFieldTypes:false})}

Source

Completely replace the webpack config for the current stage. This can bedangerous and break Gatsby if certain configuration options are changed.

Generally only useful for cases where you need to handle config merging logicyourself, in which case consider usingwebpack-merge.

Parameters

  • configObject

    complete webpack config

  • plugin

Source

Set top-level Babel options. Plugins and presets will be ignored. UsesetBabelPlugin and setBabelPreset for this.

Parameters

  • optionsObject
  • plugin
  • configObject

    An options object in the shape of a normal babelrc JavaScript object

Example

setBabelOptions({options:{sourceMaps:`inline`,}})

Source

Add new plugins or merge options into existing Babel plugins.

Parameters

  • configObject

    A config object describing the Babel plugin to be added.

    • namestring

      The name of the Babel plugin

    • optionsObject

      Options to pass to the Babel plugin.

  • plugin

Example

setBabelPlugin({name:`@emotion/babel-plugin`,options:{sourceMap:true,},})

Source

Add new presets or merge options into existing Babel presets.

Parameters

  • configObject

    A config object describing the Babel plugin to be added.

    • namestring

      The name of the Babel preset.

    • optionsObject

      Options to pass to the Babel preset.

  • plugin

Example

setBabelPreset({name:`@babel/preset-react`,options:{pragma:`Glamor.createElement`,},})

Source

DEPRECATED. Use createJobV2 instead.

Set (update) a “job”. Sometimes on really long running jobs you wantto update the job as it continues.

Use “createJobV2” instead

Parameters

  • jobObject

    A job object with at least an id set

    • idid

      The id of the job

  • plugin

Example

setJob({id:`write file id: 123`,progress:50})

Source

Set plugin status. A plugin can use this to save status keys e.g. the lastit fetched something. These values are persisted between runs of Gatsby.

Parameters

  • statusObject

    An object with arbitrary values set

  • pluginPlugin

Example

setPluginStatus({lastFetched: Date.now()})

Source

Stores request headers for a given domain to be later used when making requests for Image CDN (and potentially other features).

Parameters

  • destructured object
    • domainstring

      The domain to store the headers for.

    • headersObject

      The headers to store.

  • pluginPlugin

Source

Merge additional configuration into the current webpack config. A fewconfigurations options will be ignored if set, in order to try prevent accidental breakage.Specifically, any change toentry,output,target, orresolveLoaders will be ignored.

For full control over the webpack config, usereplaceWebpackConfig().

Parameters

  • configObject

    partial webpack config, to be merged into the current one

  • plugin

Source

“Touch” a node. Tells Gatsby a node still exists and shouldn’tbe garbage collected. Primarily useful for source plugins fetchingnodes from a remote system that can return only nodes that haveupdated. The source plugin then touches all the nodes that haven’tupdated but still exist so Gatsby knows to keep them.

Parameters

  • nodeObject

    A node object. See the “createNode” action for more information about the node object details.

  • pluginPlugin

Example

touchNode(node)

Source

Creates an individual node manifest.This is used to tie the unique revision state within a data source at the current point in time to a page generated from the provided node when it’s node manifest is processed.

Parameters

  • destructured object
    • manifestId
    • node
    • updatedAtUTC
  • pluginPlugin
  • manifestObject

    Manifest data

    • manifestIdstring

      An id which ties the unique revision state of this manifest to the unique revision state of a data source.

    • nodeObject

      The Gatsby node to tie the manifestId to. See the “createNode” action for more information about the node object details.

    • updatedAtUTCstring

      (optional) The time in which the node was last updated. If this parameter is not included, a manifest is created for every node that gets called. By default, node manifests are created for content updated in the last 30 days. To change this, set aNODE_MANIFEST_MAX_DAYS_OLD environment variable.

Example

unstable_createNodeManifest({manifestId:`post-id-1--updated-53154315`,updatedAtUTC:`2021-07-08T21:52:28.791+01:00`,node:{id:`post-id-1`},})

Gatsby is powered by the amazing Gatsby
community and Gatsby, the company.


[8]ページ先頭

©2009-2025 Movatter.jp