gatsby
- Version 5.14.1
- Published
- 6.99 MB
- 167 dependencies
- MIT license
Install
npm i gatsby
yarn add gatsby
pnpm add gatsby
Overview
Blazing fast modern site generator for React
Index
Functions
Classes
Interfaces
Actions
- addGatsbyImageSourceUrl()
- addRemoteFileAllowedUrl()
- addThirdPartySchema()
- createFieldExtension()
- createJob()
- createJobV2()
- createNode()
- createNodeField()
- createPage()
- createParentChildLink()
- createRedirect()
- createSlice()
- createTypes()
- deleteNode()
- deletePage()
- enableStatefulSourceNodes()
- endJob()
- printTypeDefinitions()
- replaceWebpackConfig()
- setBabelOptions()
- setBabelPlugin()
- setBabelPreset()
- setJob()
- setPluginStatus()
- setRequestHeaders()
- setWebpackConfig()
- touchNode()
- unstable_createNodeManifest()
GatsbyBrowser
- disableCorePrefetching()
- onClientEntry()
- onInitialClientRender()
- onPostPrefetchPathname()
- onPrefetchPathname()
- onPreRouteUpdate()
- onRouteUpdate()
- onRouteUpdateDelayed()
- onServiceWorkerActive()
- onServiceWorkerInstalled()
- onServiceWorkerRedundant()
- onServiceWorkerUpdateFound()
- onServiceWorkerUpdateReady()
- registerServiceWorker()
- replaceHydrateFunction()
- shouldUpdateScroll()
- wrapPageElement()
- wrapRootElement()
GatsbyNode
- createPages()
- createPagesStatefully()
- createResolvers()
- createSchemaCustomization()
- onCreateBabelConfig()
- onCreateDevServer()
- onCreateNode()
- onCreatePage()
- onCreateWebpackConfig()
- onPluginInit()
- onPostBootstrap()
- onPostBuild()
- onPreBootstrap()
- onPreBuild()
- onPreExtractQueries()
- onPreInit()
- pluginOptionsSchema()
- preprocessSource()
- resolvableExtensions()
- setFieldsOnGraphQLNodeType()
- shouldOnCreateNode()
- sourceNodes()
WebpackPlugins
- aggressiveMerging
- aggressiveSplitting
- automaticPrefetch
- banner
- cache
- chunkModuleIdRange
- contextReplacement
- dedupe
- define
- dll
- dllReference
- environment
- evalDevToolModule
- evalSourceMapDevTool
- extendedAPI
- externals
- extractText
- hashedModuleIds
- hotModuleReplacement
- ignore
- jsonpTemplate
- libraryTemplate
- limitChunkCount
- loaderOptions
- loaderTarget
- memoryOutputFile
- minChunkSize
- minifyCss
- minifyJs
- moduleConcatenation
- moduleFilenameH
- moment
- namedChunks
- namedModules
- newWatching
- noEmitOnErrors
- noErrors
- normalModuleReplacement
- occurrenceOrder
- prefetch
- progress
- provide
- setVarMainTemplate
- sourceMapDevTool
- splitChunks
- umdMainTemplate
- watchIgnore
Type Aliases
Functions
function graphql
graphql: (query: TemplateStringsArray) => StaticQueryDocument;
graphql is a tag function. Behind the scenes Gatsby handles these tags in a particular way
During the Gatsby build process, GraphQL queries are pulled out of the original source for parsing.
See Also
https://www.gatsbyjs.com/docs/page-query#how-does-the-graphql-tag-work
function parsePath
parsePath: (path: string) => WindowLocation;
function prefetchPathname
prefetchPathname: (path: string) => void;
function Slice
Slice: (props: SlicePlaceholderProps) => JSX.Element;
Component used as a slice placholder, to mark a place in the page where a [slice](https://gatsbyjs.com/docs/reference/built-in-components/gatsby-slice/) should be inserted.
function useScrollRestoration
useScrollRestoration: (key: string) => { ref: React.MutableRefObject<HTMLElement | undefined>; onScroll(): void;};
function useStaticQuery
useStaticQuery: <TData = any>(query: StaticQueryDocument) => TData;
A React Hooks version of StaticQuery.
StaticQuery can do most of the things that page query can, including fragments. The main differences are:
- page queries can accept variables (via
pageContext
) but can only be added to _page_ components - StaticQuery does not accept variables (hence the name "static"), but can be used in _any_ component, including pagesSee Also
https://www.gatsbyjs.com/docs/how-to/querying-data/use-static-query/
Classes
class PageRenderer
class PageRenderer extends React.Component<PageRendererProps> {}
PageRenderer's constructor [loads the page resources](https://www.gatsbyjs.com/docs/production-app/#load-page-resources) for the path.
On first load though, these will have already been requested from the server by
<link rel="preload" ... />
in the page's original HTML (see [Link Preloads](https://www.gatsbyjs.com/docs/how-code-splitting-works/#construct-link-and-script-tags-for-current-page) in HTML Generation Docs). The loaded page resources includes the imported component, with which we create the actual page component using [React.createElement()](https://reactjs.org/docs/react-api.html). This element is returned to our RouteHandler which hands it off to Reach Router for rendering.See Also
https://www.gatsbyjs.com/docs/production-app/#page-rendering
class StaticQuery
class StaticQuery<T = any> extends React.Component<StaticQueryProps<T>> {}
StaticQuery can do most of the things that page query can, including fragments. The main differences are:
- page queries can accept variables (via
pageContext
) but can only be added to _page_ components - StaticQuery does not accept variables (hence the name "static"), but can be used in _any_ component, including pages - StaticQuery does not work with raw React.createElement calls; please use JSX, e.g.<StaticQuery />
See Also
https://www.gatsbyjs.com/docs/static-query/
class StaticQueryDocument
class StaticQueryDocument {}
method toString
toString: () => string;
Allows type-safe access to the static query hash for debugging purposes.
Interfaces
interface Actions
interface Actions {}
method addGatsbyImageSourceUrl
addGatsbyImageSourceUrl: (this: void, sourceUrl: string) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#addGatsbyImageSourceUrl
method addRemoteFileAllowedUrl
addRemoteFileAllowedUrl: ( this: void, url: string | Array<string>, plugin?: ActionPlugin, traceId?: string) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#addRemoteFileAllowedUrl
method addThirdPartySchema
addThirdPartySchema: ( this: void, args: { schema: object }, plugin?: ActionPlugin, traceId?: string) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#addThirdPartySchema
method createFieldExtension
createFieldExtension: ( this: void, extension: object, plugin?: ActionPlugin, traceId?: string) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#createFieldExtension
method createJob
createJob: ( this: void, job: Record<string, unknown> & { id: string }, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#createJob
method createJobV2
createJobV2: ( this: void, job: { name: string; inputPaths: string[]; outputDir: string; args: Record<string, unknown>; }, plugin?: ActionPlugin) => Promise<unknown>;
See Also
https://www.gatsbyjs.com/docs/actions/#createJobV2
method createNode
createNode: <TNode = Record<string, unknown>>( this: void, node: NodeInput & TNode, plugin?: ActionPlugin, options?: ActionOptions) => void | Promise<void>;
See Also
https://www.gatsbyjs.com/docs/actions/#createNode
method createNodeField
createNodeField: ( this: void, args: { node: Node; name?: string; value: any }, plugin?: ActionPlugin, options?: ActionOptions) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#createNodeField
method createPage
createPage: <TContext = Record<string, unknown>>( this: void, args: Page<TContext>, plugin?: ActionPlugin, option?: ActionOptions) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#createPage
method createParentChildLink
createParentChildLink: ( this: void, args: { parent: Node; child: NodeInput }, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#createParentChildLink
method createRedirect
createRedirect: ( this: void, redirect: { [key: string]: unknown; fromPath: string; isPermanent?: boolean; toPath: string; redirectInBrowser?: boolean; force?: boolean; statusCode?: number; ignoreCase?: boolean; }, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#createRedirect
method createSlice
createSlice: <TContext = Record<string, unknown>>( this: void, args: SliceInput<TContext>, plugin?: ActionPlugin, option?: ActionOptions) => void;
See Also
https://www.gatsbyjs.com/docs/reference/config-files/actions/#createSlice
method createTypes
createTypes: ( this: void, types: | string | GraphQLOutputType | GatsbyGraphQLType | Array<string | GraphQLOutputType | GatsbyGraphQLType>, plugin?: ActionPlugin, traceId?: string) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#createTypes
method deleteNode
deleteNode: (node: NodeInput, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#deleteNode
method deletePage
deletePage: (this: void, args: { path: string; component: string }) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#deletePage
method enableStatefulSourceNodes
enableStatefulSourceNodes: (this: void, plugin?: ActionPlugin) => void;
Marks the source plugin that called this function as stateful. Gatsby will not check for stale nodes for any plugin that calls this.
method endJob
endJob: (this: void, job: { id: string }, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#endJob
method printTypeDefinitions
printTypeDefinitions: ( this: void, options: { path?: string; include?: { types?: Array<string>; plugins?: Array<string> }; exclude?: { types?: Array<string>; plugins?: Array<string> }; withFieldTypes?: boolean; }, plugin?: ActionPlugin, traceId?: string) => void;
method replaceWebpackConfig
replaceWebpackConfig: ( this: void, config: object, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#replaceWebpackConfig
method setBabelOptions
setBabelOptions: (this: void, options: object, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#setBabelOptions
method setBabelPlugin
setBabelPlugin: ( this: void, config: { name: string; options: object }, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#setBabelPlugin
method setBabelPreset
setBabelPreset: ( this: void, config: { name: string; options: object }, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#setBabelPreset
method setJob
setJob: ( this: void, job: Record<string, unknown> & { id: string }, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#setJob
method setPluginStatus
setPluginStatus: ( this: void, status: Record<string, unknown>, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#setPluginStatus
method setRequestHeaders
setRequestHeaders: ( this: void, args: { domain: string; headers: Record<string, string> }, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#setRequestHeaders
method setWebpackConfig
setWebpackConfig: (this: void, config: object, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#setWebpackConfig
method touchNode
touchNode: (node: NodeInput, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/actions/#touchNode
method unstable_createNodeManifest
unstable_createNodeManifest: ( this: void, args: { manifestId: string; node: Node; updatedAtUTC?: string | number }, plugin?: ActionPlugin) => void;
See Also
https://www.gatsbyjs.com/docs/reference/config-files/actions/#unstable_createNodeManifest
interface BrowserPluginArgs
interface BrowserPluginArgs {}
property getResourceURLsForPathname
getResourceURLsForPathname: Function;
index signature
[key: string]: unknown;
interface BuildArgs
interface BuildArgs extends ParentSpanPluginArgs {}
method graphql
graphql: <TData, TVariables = any>( query: string, variables?: TVariables) => Promise<{ errors?: any; data?: TData }>;
interface Cache
interface Cache {}
Deprecated
Use
GatsbyCache
instead
interface CreateBabelConfigArgs
interface CreateBabelConfigArgs extends ParentSpanPluginArgs {}
property stage
stage: GatsbyStages;
interface CreateDevServerArgs
interface CreateDevServerArgs extends ParentSpanPluginArgs {}
property app
app: any;
interface CreateNodeArgs
interface CreateNodeArgs< TNode extends Record<string, unknown> = Record<string, unknown>> extends ParentSpanPluginArgs {}
interface CreatePageArgs
interface CreatePageArgs<TContext = Record<string, unknown>> extends ParentSpanPluginArgs {}
interface CreatePagesArgs
interface CreatePagesArgs extends ParentSpanPluginArgs {}
property traceId
traceId: string;
property waitForCascadingActions
waitForCascadingActions: boolean;
method graphql
graphql: <TData, TVariables = any>( query: string, variables?: TVariables) => Promise<{ errors?: any; data?: TData }>;
interface CreateResolversArgs
interface CreateResolversArgs extends ParentSpanPluginArgs {}
property createResolvers
createResolvers: Function;
property intermediateSchema
intermediateSchema: object;
property traceId
traceId: 'initial-createResolvers';
interface CreateSchemaCustomizationArgs
interface CreateSchemaCustomizationArgs extends ParentSpanPluginArgs {}
property traceId
traceId: 'initial-createSchemaCustomization';
interface CreateWebpackConfigArgs
interface CreateWebpackConfigArgs extends ParentSpanPluginArgs {}
interface GatsbyBrowser
interface GatsbyBrowser< DataType = Record<string, unknown>, PageContext = Record<string, unknown>, LocationState = WindowLocation['state']> {}
Gatsby browser API.
See Also
https://www.gatsbyjs.com/docs/browser-apis/
method disableCorePrefetching
disableCorePrefetching: ( args: BrowserPluginArgs, options: PluginOptions) => boolean;
method onClientEntry
onClientEntry: (args: BrowserPluginArgs, options: PluginOptions) => void;
method onInitialClientRender
onInitialClientRender: (args: BrowserPluginArgs, options: PluginOptions) => void;
method onPostPrefetchPathname
onPostPrefetchPathname: ( args: PrefetchPathnameArgs, options: PluginOptions) => void;
method onPrefetchPathname
onPrefetchPathname: (args: PrefetchPathnameArgs, options: PluginOptions) => void;
method onPreRouteUpdate
onPreRouteUpdate: (args: RouteUpdateArgs, options: PluginOptions) => void;
method onRouteUpdate
onRouteUpdate: (args: RouteUpdateArgs, options: PluginOptions) => void;
method onRouteUpdateDelayed
onRouteUpdateDelayed: ( args: RouteUpdateDelayedArgs, options: PluginOptions) => void;
method onServiceWorkerActive
onServiceWorkerActive: (args: ServiceWorkerArgs, options: PluginOptions) => void;
method onServiceWorkerInstalled
onServiceWorkerInstalled: ( args: ServiceWorkerArgs, options: PluginOptions) => void;
method onServiceWorkerRedundant
onServiceWorkerRedundant: ( args: ServiceWorkerArgs, options: PluginOptions) => void;
method onServiceWorkerUpdateFound
onServiceWorkerUpdateFound: ( args: ServiceWorkerArgs, options: PluginOptions) => void;
method onServiceWorkerUpdateReady
onServiceWorkerUpdateReady: ( args: ServiceWorkerArgs, options: PluginOptions) => void;
method registerServiceWorker
registerServiceWorker: ( args: BrowserPluginArgs, options: PluginOptions) => boolean;
method replaceHydrateFunction
replaceHydrateFunction: ( args: BrowserPluginArgs, options: PluginOptions) => Renderer;
method shouldUpdateScroll
shouldUpdateScroll: ( args: ShouldUpdateScrollArgs, options: PluginOptions) => boolean | [number, number] | string;
method wrapPageElement
wrapPageElement: ( args: WrapPageElementBrowserArgs<DataType, PageContext, LocationState>, options: PluginOptions) => React.ReactElement;
method wrapRootElement
wrapRootElement: ( args: WrapRootElementBrowserArgs, options: PluginOptions) => React.ReactElement;
interface GatsbyCache
interface GatsbyCache {}
property directory
directory: string;
property name
name: string;
method del
del: (key: string) => Promise<void>;
Deletes cached value
Parameter key
Cache key
Returns
{Promise} Promise resolving once key is deleted from cache
Example 1
await cache.del(
unique-key
)
method get
get: (key: string) => Promise<any>;
Retrieve cached value
Parameter key
Cache key
Returns
Promise resolving to cached value
Example 1
const value = await cache.get(
unique-key
)
method set
set: (key: string, value: any) => Promise<any>;
Cache value
Parameter key
Cache key
Parameter value
Value to be cached
Returns
Promise resolving to cached value
Example 1
await cache.set(
unique-key
, value)
interface GatsbyConfig
interface GatsbyConfig {}
Gatsby configuration API.
See Also
https://www.gatsbyjs.com/docs/reference/config-files/gatsby-config/
property adapter
adapter?: IAdapter;
Adapters are responsible for taking the production output from Gatsby and turning it into something your deployment platform understands. They make it easier to build and deploy Gatsby on any deployment platform.
See Also
http://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting/adapters/
property assetPrefix
assetPrefix?: string;
In some circumstances you may want to deploy assets (non-HTML resources such as JavaScript, CSS, etc.) to a separate domain.
assetPrefix
allows you to use Gatsby with assets hosted from a separate domain
property flags
flags?: Record<string, boolean>;
You can activate and deactivate current experiments here. These are experimental features that are currently under development and need testing. When opting in to an experiment you'll receive a console message with more information of what it does and a link to an umbrella discussion.
property graphqlTypegen
graphqlTypegen?: boolean | GraphQLTypegenOptions;
More easily incorporate content into your pages through automatic TypeScript type generation and better GraphQL IntelliSense. If set to true, the default GraphQLTypegenOptions are used. See https://www.gatsbyjs.com/docs/reference/config-files/gatsby-config/ for all options.
property headers
headers?: Array<Header>;
You can set custom HTTP headers on the response of a given path. This allows you to, e.g. modify the caching behavior or configure access control. You can apply HTTP headers to static routes and redirects.
See Also
http://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting/headers/
property jsxImportSource
jsxImportSource?: string;
property jsxRuntime
jsxRuntime?: 'automatic' | 'classic';
property mapping
mapping?: Record<string, string>;
property partytownProxiedURLs
partytownProxiedURLs?: Array<string>;
A list of trusted URLs that will be proxied for use with the gatsby-script off-main-thread strategy.
See Also
https://gatsby.dev/gatsby-script
property pathPrefix
pathPrefix?: string;
It’s common for sites to be hosted somewhere other than the root of their domain. Say we have a Gatsby site at
example.com/blog/
. In this case, we would need a prefix (/blog
) added to all paths on the site.
property plugins
plugins?: Array<PluginRef>;
Plugins are Node.js packages that implement Gatsby APIs. The config file accepts an array of plugins. Some plugins may need only to be listed by name, while others may take options.
property polyfill
polyfill?: boolean;
Gatsby uses the ES6 Promise API. Because some browsers don't support this, Gatsby includes a Promise polyfill by default. If you'd like to provide your own Promise polyfill, you can set
polyfill
to false.
property proxy
proxy?: Proxy | Proxy[];
Setting the proxy config option will tell the develop server to proxy any unknown requests to your specified server.
See Also
https://www.gatsbyjs.com/docs/api-proxy/
property siteMetadata
siteMetadata?: Record<string, unknown>;
When you want to reuse common pieces of data across the site (for example, your site title), you can store that here.
property trailingSlash
trailingSlash?: 'always' | 'never' | 'ignore';
never
removes all trailing slashes,always
adds it, andignore
doesn't automatically change anything and it's in user hands to keep things consistent. By defaultalways
is used.
method developMiddleware
developMiddleware: (app: any) => void;
Sometimes you need more granular/flexible access to the development server. Gatsby exposes the Express.js development server to your site’s gatsby-config.js where you can add Express middleware as needed.
interface GatsbyFunctionBodyParserCommonMiddlewareConfig
interface GatsbyFunctionBodyParserCommonMiddlewareConfig {}
interface GatsbyFunctionBodyParserConfig
interface GatsbyFunctionBodyParserConfig {}
property json
json?: GatsbyFunctionBodyParserCommonMiddlewareConfig;
property raw
raw?: GatsbyFunctionBodyParserCommonMiddlewareConfig;
property text
text?: GatsbyFunctionBodyParserCommonMiddlewareConfig;
property urlencoded
urlencoded?: GatsbyFunctionBodyParserUrlencodedConfig;
interface GatsbyFunctionBodyParserUrlencodedConfig
interface GatsbyFunctionBodyParserUrlencodedConfig extends GatsbyFunctionBodyParserCommonMiddlewareConfig {}
property extended
extended: boolean;
interface GatsbyFunctionConfig
interface GatsbyFunctionConfig {}
property bodyParser
bodyParser?: GatsbyFunctionBodyParserConfig;
interface GatsbyFunctionRequest
interface GatsbyFunctionRequest<ReqBody = any> extends IncomingMessage {}
Gatsby function route request
property body
body: ReqBody;
property cookies
cookies: Record<string, string>;
Object of
cookies
from header
property params
params: Record<string, string>;
Object of values from route parameters
property query
query: Record<string, string>;
Object of values from URL query parameters (after the ? in the URL)
property rawUrl
rawUrl?: string;
Optional field to store the full raw URL by adapters
interface GatsbyFunctionResponse
interface GatsbyFunctionResponse<T = any> extends ServerResponse {}
Gatsby Function route response
property json
json: Send<T>;
Send
JSON
data in response
property send
send: Send<T>;
Send
any
data in response
property status
status: (statusCode: number) => GatsbyFunctionResponse<T>;
Set the HTTP status code of the response
method redirect
redirect: { (url: string): GatsbyFunctionResponse<T>; (status: number, url: string): GatsbyFunctionResponse<T>;};
interface GatsbyGraphQLEnumType
interface GatsbyGraphQLEnumType {}
interface GatsbyGraphQLInputObjectType
interface GatsbyGraphQLInputObjectType {}
interface GatsbyGraphQLInterfaceType
interface GatsbyGraphQLInterfaceType {}
interface GatsbyGraphQLObjectType
interface GatsbyGraphQLObjectType {}
interface GatsbyGraphQLScalarType
interface GatsbyGraphQLScalarType {}
interface GatsbyGraphQLUnionType
interface GatsbyGraphQLUnionType {}
interface GatsbyNode
interface GatsbyNode< TNode extends Record<string, unknown> = Record<string, unknown>, TContext = Record<string, unknown>> {}
Gatsby API for Node.js.
See Also
https://www.gatsbyjs.com/docs/node-apis/
method createPages
createPages: ( args: CreatePagesArgs & { traceId: 'initial-createPages' }, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
Tell plugins to add pages. This extension point is called only after the initial sourcing and transformation of nodes plus creation of the GraphQL schema are complete so you can query your data in order to create pages.
See Also
https://www.gatsbyjs.com/docs/node-apis/#createPages
method createPagesStatefully
createPagesStatefully: ( args: CreatePagesArgs & { traceId: 'initial-createPagesStatefully' }, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
Like
createPages
but for plugins who want to manage creating and removing pages themselves in response to changes in data *not* managed by Gatsby. Plugins implementingcreatePages
will get called regularly to recompute page information as Gatsby's data changes but those implementingcreatePagesStatefully
will not.An example of a plugin that uses this extension point is the plugin [gatsby-plugin-page-creator](https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-plugin-page-creator) which monitors the
src/pages
directory for the adding and removal of JS pages. As its source of truth, files in the pages directory, is not known by Gatsby, it needs to keep its own state about its world to know when to add and remove pages.
method createResolvers
createResolvers: ( args: CreateResolversArgs, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
Add custom field resolvers to the GraphQL schema.
Allows adding new fields to types by providing field configs, or adding resolver functions to existing fields.
Things to note: * Overriding field types is disallowed, instead use the
createTypes
action. In case of types added from third-party schemas, where this is not possible, overriding field types is allowed. * New fields will not be available onfilter
andsort
input types. Extend types defined withcreateTypes
if you need this. * In field configs, types can be referenced as strings. * When extending a field with an existing field resolver, the original resolver function is available frominfo.originalResolver
. * ThecreateResolvers
API is called as the last step in schema generation. Thus, an intermediate schema is made available on theschema
property. In resolver functions themselves, it is recommended to access the final built schema frominfo.schema
. * Gatsby's data layer, including all internal query capabilities, is exposed on [context.nodeModel
](/docs/node-model/). The node store can be queried directly withfindOne
,getNodeById
andgetNodesByIds
, while more advanced queries can be composed withfindAll
. * It is possible to add fields to the rootQuery
type. * When using the first resolver argument (source
in the example below, often also calledparent
orroot
), take care of the fact that field resolvers can be called more than once in a query, e.g. when the field is present both in the input filter and in the selection set. This means that foreign-key fields onsource
can be either resolved or not-resolved.For fuller examples, see [
using-type-definitions
](https://github.com/gatsbyjs/gatsby/tree/master/examples/using-type-definitions).See Also
https://www.gatsbyjs.com/docs/reference/config-files/gatsby-node/#createResolvers
method createSchemaCustomization
createSchemaCustomization: ( args: CreateSchemaCustomizationArgs, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
Customize Gatsby’s GraphQL schema by creating type definitions, field extensions or adding third-party schemas. The createTypes, createFieldExtension and addThirdPartySchema actions are only available in this API.
For details on their usage please refer to the actions documentation.
This API runs immediately before schema generation. For modifications of the generated schema, e.g. to customize added third-party types, use the createResolvers API.
See Also
https://www.gatsbyjs.com/docs/node-apis/#createSchemaCustomization
method onCreateBabelConfig
onCreateBabelConfig: ( args: CreateBabelConfigArgs, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
Let plugins extend/mutate the site's Babel configuration. This API will change before 2.0 as it needs still to be converted to use Redux actions.
method onCreateDevServer
onCreateDevServer: ( args: CreateDevServerArgs, options: PluginOptions, calllback: PluginCallback<void>) => void | Promise<void>;
Run when gatsby develop server is started, its useful to add proxy and middleware to the dev server app
Parameter $0
Parameter
{Express} $0.app The [Express app](https://expressjs.com/en/4x/api.html#app) used to run the dev server
Example 1
exports.onCreateDevServer = ({ app }) => { app.get('/hello', function (req, res) { res.send('hello world') }) }
method onCreateNode
onCreateNode: ( args: CreateNodeArgs<TNode>, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
Called when a new node is created. Plugins wishing to extend or transform nodes created by other plugins should implement this API.
See also the documentation for
createNode
and [createNodeField
](https://www.gatsbyjs.com/docs/reference/config-files/actions/#createNodeField)Parameter $0
Parameter
{object} $0.node A node object.
Parameter
{object} $0.actions
Parameter
{function} $0.actions.createNode Create a new node.
Parameter
{function} $0.actions.createNodeField Extend another node. The new node field is placed under the fields key on the extended node object.
Example 1
exports.onCreateNode = ({ node, getNode, actions }) => { const { createNodeField } = actions
if (node.internal.type ===
MarkdownRemark
) { const nodePath = node.fileAbsolutePathif (nodePath.match(//blog//)) { const postSlug = createFilePath({ node, getNode, basePath:
src/content
, trailingSlash: true, })createNodeField({ node, name:
slug
, value:/blog/${postSlug}/
, }) } } }
method onCreatePage
onCreatePage: ( args: CreatePageArgs<TContext>, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
Called when a new page is created. This extension API is useful for programmatically manipulating pages created by other plugins e.g. if you want paths without trailing slashes.
See the guide [Creating and Modifying Pages](https://www.gatsbyjs.com/docs/creating-and-modifying-pages/) for more on this API.
method onCreateWebpackConfig
onCreateWebpackConfig: ( args: CreateWebpackConfigArgs, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
Let plugins extend/mutate the site's webpack configuration.
See Also
https://www.gatsbyjs.com/docs/node-apis/#onCreateWebpackConfig
method onPluginInit
onPluginInit: ( args: ParentSpanPluginArgs, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
Lifecycle executed in each process (one time per process). Used to store actions, etc. for later use. Plugins should use this over other APIs like "onPreBootstrap" or "onPreInit" since onPluginInit will run in main process + all workers to support Parallel Query Running. 3.9.0
Example 1
let createJobV2 exports.onPluginInit = ({ actions }) => { // Store job creation action to use it later createJobV2 = actions.createJobV2 }
method onPostBootstrap
onPostBootstrap: ( args: ParentSpanPluginArgs, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
Called at the end of the bootstrap process after all other extension APIs have been called.
method onPostBuild
onPostBuild: ( args: BuildArgs, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
The last extension point called after all other parts of the build process are complete.
method onPreBootstrap
onPreBootstrap: ( args: ParentSpanPluginArgs, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
Called at the end of the bootstrap process after all other extension APIs have been called. If you indend to use this API in a plugin, use "onPluginInit" instead.
method onPreBuild
onPreBuild: ( args: BuildArgs, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
The first extension point called during the build process. Called after the bootstrap has completed but before the build steps start.
method onPreExtractQueries
onPreExtractQueries: ( args: ParentSpanPluginArgs, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
Called once Gatsby has initialized itself and is ready to bootstrap your site.
method onPreInit
onPreInit: ( args: PreInitArgs, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
The first API called during Gatsby execution, runs as soon as plugins are loaded, before cache initialization and bootstrap preparation. If you indend to use this API in a plugin, use "onPluginInit" instead.
method pluginOptionsSchema
pluginOptionsSchema: (args: PluginOptionsSchemaArgs) => ObjectSchema;
Add a Joi schema for the possible options of your plugin. Currently experimental and not enabled by default.
method preprocessSource
preprocessSource: ( args: PreprocessSourceArgs, options: PluginOptions, callback: PluginCallback<void>) => void | string | Promise<void | string>;
Ask compile-to-js plugins to process source to JavaScript so the query runner can extract out GraphQL queries for running.
method resolvableExtensions
resolvableExtensions: ( args: ResolvableExtensionsArgs, options: PluginOptions, callback: PluginCallback<Array<string>>) => Array<string> | Promise<Array<string>>;
Lets plugins implementing support for other compile-to-js add to the list of "resolvable" file extensions. Gatsby supports
.js
and.jsx
by default.
method setFieldsOnGraphQLNodeType
setFieldsOnGraphQLNodeType: ( args: SetFieldsOnGraphQLNodeTypeArgs, options: PluginOptions, callback: PluginCallback<any>) => any;
Called during the creation of the GraphQL schema. Allows plugins to add new fields to the types created from data nodes. It will be called separately for each type.
This function should return an object in the shape of [GraphQLFieldConfigMap](https://graphql.org/graphql-js/type/#graphqlobjecttype) which will be appended to fields inferred by Gatsby from data nodes.
*Note:* Import GraphQL types from
gatsby/graphql
and don't add thegraphql
package to your project/plugin dependencies to avoid Schema must contain unique named types but contains multiple types named errors.gatsby/graphql
exports all builtin GraphQL types as well as thegraphQLJSON
type.Many transformer plugins use this to add fields that take arguments.
See Also
https://www.gatsbyjs.com/docs/node-apis/#setFieldsOnGraphQLNodeType
method shouldOnCreateNode
shouldOnCreateNode: (args: { node: TNode }, options: PluginOptions) => boolean;
Called before scheduling a
onCreateNode
callback for a plugin. If it returns falsy then Gatsby will not schedule theonCreateNode
callback for this node for this plugin. Note: this API does not receive the regularapi
that other callbacks get as first arg.2.24.80
Example 1
exports.shouldOnCreateNode = ({node}, pluginOptions) => node.internal.type === 'Image'
method sourceNodes
sourceNodes: ( args: SourceNodesArgs, options: PluginOptions, callback: PluginCallback<void>) => void | Promise<void>;
Extension point to tell plugins to source nodes. This API is called during the Gatsby bootstrap sequence. Source plugins use this hook to create nodes. This API is called exactly once per plugin (and once for your site's
gatsby-config.js
file). If you define this hook ingatsby-node.js
it will be called exactly once after all of your source plugins have finished creating nodes.See Also
https://www.gatsbyjs.com/docs/node-apis/#sourceNodes
interface GatsbySSR
interface GatsbySSR< DataSet = Record<string, unknown>, PageContext = Record<string, unknown>> {}
Gatsby server-side rendering API.
See Also
https://www.gatsbyjs.com/docs/ssr-apis/
method onPreRenderHTML
onPreRenderHTML: (args: PreRenderHTMLArgs, options: PluginOptions) => void;
Called after every page Gatsby server renders while building HTML so you can replace head components to be rendered in your
html.js
. This is useful if you need to reorder scripts or styles added by other plugins.Example 1
// Move Typography.js styles to the top of the head section so they're loaded first. exports.onPreRenderHTML = ({ getHeadComponents, replaceHeadComponents }) => { const headComponents = getHeadComponents() headComponents.sort((x, y) => { if (x.key === 'TypographyStyle') { return -1 } else if (y.key === 'TypographyStyle') { return 1 } return 0 }) replaceHeadComponents(headComponents) }
method onRenderBody
onRenderBody: (args: RenderBodyArgs, options: PluginOptions) => void;
Called after every page Gatsby server renders while building HTML so you can set head and body components to be rendered in your
html.js
.Gatsby does a two-pass render for HTML. It loops through your pages first rendering only the body and then takes the result body HTML string and passes it as the
body
prop to yourhtml.js
to complete the render.It's often handy to be able to send custom components to your
html.js
. For example, it's a very common pattern for React.js libraries that support server rendering to pull out data generated during the render to add to your HTML.Using this API over
replaceRenderer
is preferable as multiple plugins can implement this API where only one plugin can take over server rendering. However, if your plugin requires taking over server rendering then that's the one to useExample 1
const { Helmet } = require("react-helmet")
exports.onRenderBody = ( { setHeadComponents, setHtmlAttributes, setBodyAttributes }, pluginOptions ) => { const helmet = Helmet.renderStatic() setHtmlAttributes(helmet.htmlAttributes.toComponent()) setBodyAttributes(helmet.bodyAttributes.toComponent()) setHeadComponents([ helmet.title.toComponent(), helmet.link.toComponent(), helmet.meta.toComponent(), helmet.noscript.toComponent(), helmet.script.toComponent(), helmet.style.toComponent(), ]) }
method replaceRenderer
replaceRenderer: ( args: ReplaceRendererArgs, options: PluginOptions) => void | Promise<void>;
Replace the default server renderer. This is useful for integration with Redux, css-in-js libraries, etc. that need custom setups for server rendering.
Example 1
// From gatsby-plugin-glamor const { renderToString } = require("react-dom/server") const inline = require("glamor-inline")
exports.replaceRenderer = ({ bodyComponent, replaceBodyHTMLString }) => { const bodyHTML = renderToString(bodyComponent) const inlinedHTML = inline(bodyHTML)
replaceBodyHTMLString(inlinedHTML) }
method wrapPageElement
wrapPageElement: ( args: WrapPageElementNodeArgs<DataSet, PageContext>, options: PluginOptions) => React.ReactElement;
Allow a plugin to wrap the page element.
This is useful for setting wrapper component around pages that won't get unmounted on page change. For setting Provider components use
wrapRootElement
._Note:_ [There is equivalent hook in Browser API](https://www.gatsbyjs.com/docs/browser-apis/#wrapPageElement)
Example 1
const React = require("react") const Layout = require("./src/components/layout")
exports.wrapPageElement = ({ element, props }) => { // props provide same data to Layout as Page element will get // including location, data, etc - you don't need to pass it return <Layout {...props}>{element} }
method wrapRootElement
wrapRootElement: ( args: WrapRootElementNodeArgs, options: PluginOptions) => React.ReactElement;
Allow a plugin to wrap the root element.
This is useful to setup any Providers component that will wrap your application. For setting persistent UI elements around pages use
wrapPageElement
._Note:_ [There is equivalent hook in Browser API](https://www.gatsbyjs.com/docs/browser-apis/#wrapRootElement)
Example 1
const React = require("react") const { Provider } = require("react-redux")
const createStore = require("./src/state/createStore") const store = createStore()
exports.wrapRootElement = ({ element }) => { return ( <Provider store={store}> {element} ) }
interface GraphQLTypegenOptions
interface GraphQLTypegenOptions {}
property documentSearchPaths
documentSearchPaths?: string[];
property generateOnBuild
generateOnBuild?: boolean;
property typesOutputPath
typesOutputPath?: string;
interface IAdapter
interface IAdapter {}
property adapt
adapt: (context: IAdaptContext) => Promise<void> | void;
Hook to take Gatsby’s output and preparing it for deployment on the adapter’s platform. Executed as one of the last steps in the build process.
The
adapt
hook should do the following things: - Apply HTTP headers to assets - Apply redirects and rewrites. The adapter should can also create its own redirects/rewrites if necessary (e.g. mapping serverless functions to internal URLs). - Wrap serverless functions coming from Gatsby with platform-specific code (if necessary). Gatsby will produce [Express-like](https://expressjs.com/) handlers. - Apply trailing slash behavior and path prefix to URLs - Possibly upload assets to CDNSee Also
http://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting/creating-an-adapter/
property cache
cache?: { /** * Hook to restore `directories` from previous builds. This is executed very early on in the build process. If `false` is returned Gatsby will skip its cache restoration. */ restore: ( context: ICacheContext ) => Promise<boolean | void> | boolean | void; /** * Hook to store `directories` for the current build. Executed as one of the last steps in the build process. */ store: (context: ICacheContext) => Promise<void> | void;};
property config
config?: (context: IDefaultContext) => Promise<IAdapterConfig> | IAdapterConfig;
Hook to pass information from the adapter to Gatsby. You must return an object with a predefined shape. Gatsby uses this information to adjust its build process. The information can be e.g. things that are only known once the project is deployed.
This hook can enable advanced feature of adapters and it is not required to implement it.
See Also
http://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting/creating-an-adapter/
property name
name: string;
Unique name of the adapter. Used to identify adapter in manifest.
interface IAdapterConfig
interface IAdapterConfig {}
property deployURL
deployURL?: string;
URL representing the unique URL for an individual deploy
property excludeDatastoreFromEngineFunction
excludeDatastoreFromEngineFunction?: boolean;
If
true
, Gatsby will not include the LMDB datastore in the serverless functions used for SSR/DSG. Instead, it will try to download the datastore from the givendeployURL
.
property fileCDNUrlGeneratorModulePath
fileCDNUrlGeneratorModulePath?: string;
Path to a CommonJS module that implements an file CDN URL generation function. This module should have a default export function that conforms to the FileCdnUrlGeneratorFn type:
Adapters should provide an absolute path to this module. See 'packages/gatsby-adapter-netlify/src/file-cdn-url-generator.ts' as an implementation example for the Netlify adapter.
property functionsArch
functionsArch?: string;
The architecture bundled functions will execute on. Usually should be
x64
. This will be used if user didn't specifyGATSBY_FUNCTIONS_ARCH
environment variable or used-functions-arch
CLI toggle. If none is defined current arch (process.arch) will be used.
property functionsPlatform
functionsPlatform?: string;
The platform bundled functions will execute on. Usually should be
linux
. This will be used if user didn't specifyGATSBY_FUNCTIONS_PLATFORM
environment variable or used-functions-platform
CLI toggle. If none is defined current platform (process.platform) will be used.
property imageCDNUrlGeneratorModulePath
imageCDNUrlGeneratorModulePath?: string;
Path to a CommonJS module that implements an image CDN URL generation function. The function is used to optimize image delivery by generating URLs that leverage CDN capabilities. This module should have a default export function that conforms to the ImageCdnUrlGeneratorFn type:
Adapters should provide an absolute path to this module. See 'packages/gatsby-adapter-netlify/src/image-cdn-url-generator.ts' as an implementation example for the Netlify adapter.
property pluginsToDisable
pluginsToDisable?: Array<string>;
List of plugins that should be disabled when using this adapter. Purpose of this is to disable any potential plugins that serve similar role as adapter that would cause conflicts when both plugin and adapter is used at the same time.
property supports
supports?: { /** * If `false`, Gatsby will fail the build if user tries to use pathPrefix. */ pathPrefix?: boolean; /** * Provide array of supported traling slash options * @example [`always`] */ trailingSlash?: Array<TrailingSlash>;};
Adapters can optionally describe which features they support to prevent potentially faulty deployments
interface IFunctionDefinition
interface IFunctionDefinition {}
property functionId
functionId: string;
Unique identifier of this function. Corresponds to the
functionId
inside theroutesManifest
.
property name
name: string;
Unique name of this function. Use this as a display name for the function.
property pathToEntryPoint
pathToEntryPoint: string;
Path to function entrypoint that will be used to create function
property requiredFiles
requiredFiles: Array<string>;
List of all required files that this function needs to run
interface IFunctionRoute
interface IFunctionRoute extends IBaseRoute {}
property cache
cache?: true;
If
cache
is true, response of function should be cached for current deployment and served on subsequent requests for this route.
property functionId
functionId: string;
Unique identifier of this function. Corresponds to the
functionId
inside thefunctionsManifest
. Some functions will be shared for multiple routes, e.g. SSR or DSG functions.
property type
type: `function`;
interface IPluginRefObject
interface IPluginRefObject {}
interface IPluginRefOptions
interface IPluginRefOptions {}
property path
path?: string;
property plugins
plugins?: PluginRef[];
index signature
[option: string]: unknown;
interface IRedirectRoute
interface IRedirectRoute extends IBaseRoute {}
Redirects are being created through the
createRedirect
action.See Also
https://www.gatsbyjs.com/docs/reference/config-files/actions/#createRedirect
property headers
headers: IHeader['headers'];
HTTP headers that should be used for this redirect.
See Also
http://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting/headers/
property ignoreCase
ignoreCase?: boolean;
property status
status: HttpStatusCode;
HTTP status code that should be used for this redirect.
property toPath
toPath: string;
The redirect should happen from
path
totoPath
.
property type
type: `redirect`;
index signature
[key: string]: unknown;
interface IStaticRoute
interface IStaticRoute extends IBaseRoute {}
interface Node
interface Node extends NodeInput {}
property children
children: string[];
property internal
internal: NodeInput['internal'] & { owner: string;};
property parent
parent: string | null;
index signature
[key: string]: unknown;
interface NodeInput
interface NodeInput {}
property children
children?: string[];
property id
id: string;
property internal
internal: { type: string; mediaType?: string; content?: string; contentDigest: string; description?: string; contentFilePath?: string;};
property parent
parent?: string | null;
index signature
[key: string]: unknown;
interface NodePluginArgs
interface NodePluginArgs {}
property actions
actions: Actions;
Collection of functions used to programmatically modify Gatsby’s internal state.
property basePath
basePath: string;
This is the same as
pathPrefix
passed ingatsby-config.js
. It's an empty string if you don't passpathPrefix
. When using assetPrefix, you can use this instead of pathPrefix to recieve the string you set ingatsby-config.js
. It won't include theassetPrefix
.
property cache
cache: GatsbyCache;
Key-value store used to persist results of time/memory/cpu intensive tasks. All functions are async and return promises.
property emitter
emitter: EventEmitter;
Internal event emitter / listener. Do not use, unless you absolutely must. Emitter is considered a private API and can change with any version.
property pathPrefix
pathPrefix: string;
Use to prefix resources URLs.
pathPrefix
will be either empty string or path that starts with slash and doesn't end with slash.pathPrefix
also becomes<assetPrefix>/<pathPrefix>
when you pass bothassetPrefix
andpathPrefix
in yourgatsby-config.js
.See [Adding a Path Prefix](https://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting/path-prefix/) page for details about path prefixing.
property reporter
reporter: Reporter;
Set of utilities to output information to user
property schema
schema: NodePluginSchema;
property store
store: Store;
Internal redux state used for application state. Do not use, unless you absolutely must. Store is considered a private API and can change with any version.
property tracing
tracing: Tracing;
Set of utilities that allow adding more detailed tracing for plugins. Check [Performance tracing](https://www.gatsbyjs.com/docs/performance-tracing) page for more details.
method createContentDigest
createContentDigest: (this: void, input: string | object) => string;
Create a stable content digest from a string or object, you can use the result of this function to set the
internal.contentDigest
field on nodes. Gatsby uses the value of this field to invalidate stale data when your content changes.Parameter input
Returns
Hash string
Example 1
const node = { ...nodeData, internal: { type:
TypeOfNode
, contentDigest: createContentDigest(nodeData) } }
method createNodeId
createNodeId: (this: void, input: string) => string;
Utility function useful to generate globally unique and stable node IDs. It will generate different IDs for different plugins if they use same input.
Returns
UUIDv5 ID string
Example 1
const node = { id: createNodeId(
${backendData.type}${backendData.id}
), ...restOfNodeData }
method getCache
getCache: (this: void, id: string) => GatsbyCache;
Get cache instance by name - this should only be used by plugins that accept subplugins.
Parameter id
id of the node
Returns
See [cache](https://www.gatsbyjs.com/docs/reference/config-files/node-api-helpers/#cache) section for reference.
method getNode
getNode: (this: void, id: string) => Node | undefined;
Get single node by given ID. Don't use this in graphql resolvers - see
getNodeAndSavePathDependency
Parameter id
id of the node.
Returns
Single node instance.
Example 1
const node = getNode(id)
method getNodeAndSavePathDependency
getNodeAndSavePathDependency: (this: void, id: string, path: string) => Node;
Get single node by given ID and create dependency for given path. This should be used instead of
getNode
in graphql resolvers to enable tracking dependencies for query results. If it's not used Gatsby will not rerun query if node changes leading to stale query results. See [Page -> Node Dependency Tracking](/docs/page-node-dependencies/) for more details.Parameter id
id of the node.
Parameter path
of the node.
Returns
Single node instance.
method getNodes
getNodes: (this: void) => Node[];
Get array of all nodes.
Returns
Array of nodes.
Example 1
const allNodes = getNodes()
method getNodesByType
getNodesByType: (this: void, type: string) => Node[];
Get array of nodes of given type.
Parameter type
Type of nodes
Returns
Array of nodes.
Example 1
const markdownNodes = getNodesByType(
MarkdownRemark
)
method loadNodeContent
loadNodeContent: (this: void, node: Node) => Promise<string>;
Get content for a node from the plugin that created it.
Example 1
module.exports = async function onCreateNode( { node, loadNodeContent, actions, createNodeId } ) { if (node.internal.mediaType === 'text/markdown') { const { createNode, createParentChildLink } = actions const textContent = await loadNodeContent(node) // process textContent and create child nodes } }
index signature
[key: string]: unknown;
interface NodePluginSchema
interface NodePluginSchema {}
method buildEnumType
buildEnumType: (config: ComposeEnumTypeConfig) => GatsbyGraphQLEnumType;
method buildInputObjectType
buildInputObjectType: ( config: ComposeInputObjectTypeConfig) => GatsbyGraphQLInputObjectType;
method buildInterfaceType
buildInterfaceType: ( config: ComposeInterfaceTypeConfig<any, any>) => GatsbyGraphQLInterfaceType;
method buildObjectType
buildObjectType: ( config: ComposeObjectTypeConfig<any, any>) => GatsbyGraphQLObjectType;
method buildScalarType
buildScalarType: (config: ComposeScalarTypeConfig) => GatsbyGraphQLScalarType;
method buildUnionType
buildUnionType: ( config: ComposeUnionTypeConfig<any, any>) => GatsbyGraphQLUnionType;
interface PackageJson
interface PackageJson {}
property author
author?: | string | { name: string; email: string; };
property bundledDependencies
bundledDependencies?: Array<string>;
property dependencies
dependencies?: Record<string, string>;
property description
description?: string;
property devDependencies
devDependencies?: Record<string, string>;
property keywords
keywords?: string[];
property license
license?: string;
property main
main?: string;
property name
name?: string;
property optionalDependencies
optionalDependencies?: Record<string, string>;
property peerDependencies
peerDependencies?: Record<string, string>;
property version
version?: string;
interface Page
interface Page<TContext = Record<string, unknown>> {}
interface PageRendererProps
interface PageRendererProps {}
Constructor arguments for the PageRenderer.
property location
location: WindowLocation;
interface ParentSpanPluginArgs
interface ParentSpanPluginArgs extends NodePluginArgs {}
property parentSpan
parentSpan: Span;
interface PluginOptions
interface PluginOptions {}
property plugins
plugins: unknown[];
index signature
[key: string]: unknown;
interface PluginOptionsSchemaArgs
interface PluginOptionsSchemaArgs {}
property Joi
Joi: PluginOptionsSchemaJoi;
interface PrefetchPathnameArgs
interface PrefetchPathnameArgs extends BrowserPluginArgs {}
property pathname
pathname: string;
interface PreInitArgs
interface PreInitArgs extends ParentSpanPluginArgs {}
property actions
actions: Actions;
interface PreprocessSourceArgs
interface PreprocessSourceArgs extends ParentSpanPluginArgs {}
interface PreRenderHTMLArgs
interface PreRenderHTMLArgs {}
property getHeadComponents
getHeadComponents: () => React.ReactNode[];
property getPostBodyComponents
getPostBodyComponents: () => React.ReactNode[];
property getPreBodyComponents
getPreBodyComponents: () => React.ReactNode[];
property pathname
pathname: string;
property replaceHeadComponents
replaceHeadComponents: (comp: React.ReactNode[]) => void;
property replacePostBodyComponents
replacePostBodyComponents: (comp: React.ReactNode[]) => void;
property replacePreBodyComponents
replacePreBodyComponents: (comp: React.ReactNode[]) => void;
interface RenderBodyArgs
interface RenderBodyArgs {}
property loadPageDataSync
loadPageDataSync: (pathname: string) => { result: Record<string, unknown> };
property pathname
pathname: string;
property setBodyAttributes
setBodyAttributes: (attr: ReactProps<HTMLBodyElement>) => void;
property setBodyProps
setBodyProps: Function;
property setHeadComponents
setHeadComponents: (comp: React.ReactNode[]) => void;
property setHtmlAttributes
setHtmlAttributes: (attr: ReactProps<HTMLHtmlElement>) => void;
property setPostBodyComponents
setPostBodyComponents: (comp: React.ReactNode[]) => void;
property setPreBodyComponents
setPreBodyComponents: (comp: React.ReactNode[]) => void;
interface ReplaceRendererArgs
interface ReplaceRendererArgs {}
property bodyComponent
bodyComponent: React.ReactNode;
property pathname
pathname: string;
property replaceBodyHTMLString
replaceBodyHTMLString: (str: string) => void;
property setBodyAttributes
setBodyAttributes: (attr: ReactProps<HTMLBodyElement>) => void;
property setBodyProps
setBodyProps: Function;
property setHeadComponents
setHeadComponents: (comp: React.ReactNode[]) => void;
property setHtmlAttributes
setHtmlAttributes: (attr: ReactProps<HTMLHtmlElement>) => void;
property setPostBodyComponents
setPostBodyComponents: (comp: React.ReactNode[]) => void;
property setPreBodyComponents
setPreBodyComponents: (comp: React.ReactNode[]) => void;
interface ResolvableExtensionsArgs
interface ResolvableExtensionsArgs extends ParentSpanPluginArgs {}
property traceId
traceId: 'initial-resolvableExtensions';
interface RouteUpdateArgs
interface RouteUpdateArgs extends BrowserPluginArgs {}
property location
location: Location;
property prevLocation
prevLocation: Location | null;
interface RouteUpdateDelayedArgs
interface RouteUpdateDelayedArgs extends BrowserPluginArgs {}
property location
location: Location;
interface ServiceWorkerArgs
interface ServiceWorkerArgs extends BrowserPluginArgs {}
property serviceWorker
serviceWorker: ServiceWorkerRegistration;
interface SetFieldsOnGraphQLNodeTypeArgs
interface SetFieldsOnGraphQLNodeTypeArgs extends ParentSpanPluginArgs {}
interface ShouldUpdateScrollArgs
interface ShouldUpdateScrollArgs extends BrowserPluginArgs {}
property getSavedScrollPosition
getSavedScrollPosition: Function;
property pathname
pathname: string;
property prevRouterProps
prevRouterProps?: { location: Location;};
property routerProps
routerProps: { location: Location & NavigateOptions<any>;};
interface SliceInput
interface SliceInput<TContext = Record<string, unknown>> {}
interface SlicePlaceholderProps
interface SlicePlaceholderProps {}
A props object for [slice placholder](https://gatsbyjs.com/docs/reference/built-in-components/gatsby-slice/)
property alias
alias: string;
property allowEmpty
allowEmpty?: boolean;
property children
children?: React.ReactNode;
index signature
[key: string]: SerializableProps | React.ReactNode;
interface SourceNodesArgs
interface SourceNodesArgs extends ParentSpanPluginArgs {}
property traceId
traceId: 'initial-sourceNodes';
property waitForCascadingActions
waitForCascadingActions: boolean;
property webhookBody
webhookBody: any;
interface StaticQueryProps
interface StaticQueryProps<T = any> {}
interface Store
interface Store {}
property dispatch
dispatch: Function;
property getState
getState: Function;
property replaceReducer
replaceReducer: Function;
property subscribe
subscribe: Function;
interface Tracing
interface Tracing {}
property parentSpan
parentSpan: object;
property startSpan
startSpan: Function;
property tracer
tracer: object;
interface WebpackLoaders
interface WebpackLoaders {}
property css
css: Function;
property eslint
eslint: Function;
property exports
exports: Function;
property file
file: Function;
property imports
imports: Function;
property js
js: Function;
property json
json: Function;
property miniCssExtract
miniCssExtract: Function;
property null
null: Function;
property postcss
postcss: Function;
property raw
raw: Function;
property style
style: Function;
property url
url: Function;
property yaml
yaml: Function;
index signature
[key: string]: Function;
interface WebpackPlugins
interface WebpackPlugins {}
property aggressiveMerging
aggressiveMerging: Function;
property aggressiveSplitting
aggressiveSplitting: Function;
property automaticPrefetch
automaticPrefetch: Function;
property banner
banner: Function;
property cache
cache: Function;
property chunkModuleIdRange
chunkModuleIdRange: Function;
property contextReplacement
contextReplacement: Function;
property dedupe
dedupe: Function;
property define
define: Function;
property dll
dll: Function;
property dllReference
dllReference: Function;
property environment
environment: Function;
property evalDevToolModule
evalDevToolModule: Function;
property evalSourceMapDevTool
evalSourceMapDevTool: Function;
property extendedAPI
extendedAPI: Function;
property externals
externals: Function;
property extractText
extractText: Function;
property hashedModuleIds
hashedModuleIds: Function;
property hotModuleReplacement
hotModuleReplacement: Function;
property ignore
ignore: Function;
property jsonpTemplate
jsonpTemplate: Function;
property libraryTemplate
libraryTemplate: Function;
property limitChunkCount
limitChunkCount: Function;
property loaderOptions
loaderOptions: Function;
property loaderTarget
loaderTarget: Function;
property memoryOutputFile
memoryOutputFile: Function;
property minChunkSize
minChunkSize: Function;
property minifyCss
minifyCss: Function;
property minifyJs
minifyJs: Function;
property moduleConcatenation
moduleConcatenation: Function;
property moduleFilenameH
moduleFilenameH: Function;
property moment
moment: Function;
property namedChunks
namedChunks: Function;
property namedModules
namedModules: Function;
property newWatching
newWatching: Function;
property noEmitOnErrors
noEmitOnErrors: Function;
property noErrors
noErrors: Function;
property normalModuleReplacement
normalModuleReplacement: Function;
property occurrenceOrder
occurrenceOrder: Function;
property prefetch
prefetch: Function;
property progress
progress: Function;
property provide
provide: Function;
property setVarMainTemplate
setVarMainTemplate: Function;
property sourceMapDevTool
sourceMapDevTool: Function;
property splitChunks
splitChunks: Function;
property umdMainTemplate
umdMainTemplate: Function;
property watchIgnore
watchIgnore: Function;
index signature
[key: string]: Function;
interface WebpackRules
interface WebpackRules {}
property css
css: Function;
property cssModules
cssModules: Function;
property eslint
eslint: Function;
property fonts
fonts: Function;
property images
images: Function;
property js
js: Function;
property media
media: Function;
property miscAssets
miscAssets: Function;
property mjs
mjs: Function;
property postcss
postcss: Function;
property yaml
yaml: Function;
index signature
[key: string]: Function;
interface WrapPageElementBrowserArgs
interface WrapPageElementBrowserArgs< DataType = Record<string, unknown>, PageContextType = Record<string, unknown>, LocationState = WindowLocation['state']> extends BrowserPluginArgs {}
interface WrapPageElementNodeArgs
interface WrapPageElementNodeArgs< DataType = Record<string, unknown>, PageContextType = Record<string, unknown>> {}
interface WrapRootElementBrowserArgs
interface WrapRootElementBrowserArgs extends BrowserPluginArgs {}
interface WrapRootElementNodeArgs
interface WrapRootElementNodeArgs {}
Type Aliases
type ActivityArgs
type ActivityArgs = { parentSpan?: Object; id?: string;};
type ActivityTracker
type ActivityTracker = { start(): () => void; end(): () => void; span: Object; setStatus(status: string): void; panic: (errorMeta: string | Object, error?: Object) => never; panicOnBuild: (errorMeta: string | Object, error?: Object) => void;};
type AdapterInit
type AdapterInit<T = Record<string, unknown>> = (adapterOptions?: T) => IAdapter;
Adapter initialization function that returns an instance of the adapter.
See Also
http://www.gatsbyjs.com/docs/how-to/previews-deploys-hosting/creating-an-adapter/
type AvailableFeatures
type AvailableFeatures = | 'image-cdn' | 'graphql-typegen' | 'content-file-path' | 'stateful-source-nodes' | 'adapters';
type FunctionsManifest
type FunctionsManifest = Array<IFunctionDefinition>;
type GatsbyGraphQLType
type GatsbyGraphQLType = | GatsbyGraphQLObjectType | GatsbyGraphQLInputObjectType | GatsbyGraphQLUnionType | GatsbyGraphQLInterfaceType | GatsbyGraphQLEnumType | GatsbyGraphQLScalarType;
type GetServerData
type GetServerData<ServerDataType> = ( props: GetServerDataProps) => GetServerDataReturn<ServerDataType>;
A shorthand type for combining the props and return type for the [getServerData](https://www.gatsbyjs.com/docs/reference/rendering-options/server-side-rendering/) function.
type GetServerDataProps
type GetServerDataProps = { headers: Map<string, unknown>; method: string; url: string; query?: Record<string, unknown>; params?: Record<string, unknown>; pageContext: Record<string, unknown>;};
Props object passed into the [getServerData](https://www.gatsbyjs.com/docs/reference/rendering-options/server-side-rendering/) function.
type GetServerDataReturn
type GetServerDataReturn<ServerDataType = Record<string, unknown>> = Promise<{ headers?: Record<string, unknown>; props?: ServerDataType; status?: number;}>;
The return type (promise payload) from the [getServerData](https://www.gatsbyjs.com/docs/reference/rendering-options/server-side-rendering/) function.
type HeaderRoutes
type HeaderRoutes = Array<IHeaderRoute>;
type HeadFC
type HeadFC<DataType = object, PageContextType = object> = ( props: HeadProps<DataType, PageContextType>) => JSX.Element;
A shorthand type for combining the props and return type for the [Gatsby Head API](https://gatsby.dev/gatsby-head).
type HeadProps
type HeadProps< DataType = object, PageContextType = object, ServerDataType = object> = { location: { /** * Returns the Location object's URL's path. */ pathname: string; }; /** The URL parameters when the page has a `matchPath` */ params: Record<string, string>; /** * Data passed into the page via an exported GraphQL query. */ data: DataType; /** * A context object which is passed in during the creation of the page. */ pageContext: PageContextType; /** * Data passed into the page via the [getServerData](https://www.gatsbyjs.com/docs/reference/rendering-options/server-side-rendering/) SSR function. */ serverData: ServerDataType;};
A props object passed into the Head function for [Gatsby Head API](https://gatsby.dev/gatsby-head).
type PageProps
type PageProps< DataType = object, PageContextType = object, LocationState = WindowLocation['state'], ServerDataType = object> = { /** The path for this current page */ path: string; /** The URI for the current page */ uri: string; /** An extended version of window.document which comes from @react/router */ location: WindowLocation<LocationState>; /** You can't get passed children as this is the root user-land component */ children: undefined; /** The URL parameters when the page has a `matchPath` */ params: Record<string, string>; /** Holds information about the build process for this component */ pageResources: { component: React.Component; json: { data: DataType; pageContext: PageContextType; }; page: { componentChunkName: string; path: string; webpackCompilationHash: string; matchPath?: string; }; }; /** * Data passed into the page via an exported GraphQL query. To set up this type * you need to use [generics](https://www.typescriptlang.org/play/#example/generic-functions), * see below for an example * * @example * * import {PageProps} from "gatsby" * * type IndexQueryProps = { downloadCount: number } * type IndexPageProps = PageProps<IndexQueryProps> * * export default (props: IndexPageProps) => { * .. * */ data: DataType; /** * A context object which is passed in during the creation of the page. Can be extended if you are using * `createPage` yourself using generics: * * @example * * import {PageProps} from "gatsby" * * type IndexQueryProps = { downloadCount: number } * type LocaleLookUpInfo = { translationStrings: any } & { langKey: string, slug: string } * type IndexPageProps = PageProps<IndexQueryProps, LocaleLookUpInfo> * * export default (props: IndexPageProps) => { * .. */ pageContext: PageContextType; /** Data passed into the page via the [getServerData](https://www.gatsbyjs.com/docs/reference/rendering-options/server-side-rendering/) SSR function. */ serverData: ServerDataType;};
A props object for adding type safety to your Gatsby pages, can be extended with both the query response shape, and the page context.
Example 1
// When typing a default page from the ./pages dir
import {PageProps} from "gatsby" export default (props: PageProps) => {
Example 2
// When adding types for both pageContext (represented by LocaleLookUpInfo) // and GraphQL query data (represented by IndexQueryProps)
import {PageProps} from "gatsby"
type IndexQueryProps = { downloadCount: number } type LocaleLookUpInfo = { translationStrings: any } & { langKey: string, slug: string } type IndexPageProps = PageProps<IndexQueryProps, LocaleLookUpInfo>
export default (props: IndexPageProps) => { ..
type PluginCallback
type PluginCallback<R = any> = (err: Error | null, result?: R) => void;
type PluginRef
type PluginRef = string | IPluginRefObject;
type ProgressActivityTracker
type ProgressActivityTracker = Omit<ActivityTracker, 'end'> & { tick(increment?: number): void; done(): void; total: number;};
type RemoteFileAllowedUrls
type RemoteFileAllowedUrls = Array<{ /** * Allowed url in URLPattern format. In particular it uses wildcard `*` and param `:param` syntax. */ urlPattern: string; /** *Allowed url in regex source format */ regexSource: string;}>;
type RoutesManifest
type RoutesManifest = Array<Route>;
type SliceComponentProps
type SliceComponentProps< DataType = object, SliceContextType = object, AdditionalSerializableProps extends ISerializableObject = object> = { data: DataType; sliceContext: SliceContextType; children?: React.ReactNode;} & AdditionalSerializableProps;
A props object for [slice component](https://gatsbyjs.com/docs/reference/built-in-components/gatsby-slice/)
Package Files (2)
Dependencies (167)
- @babel/code-frame
- @babel/core
- @babel/eslint-parser
- @babel/helper-plugin-utils
- @babel/parser
- @babel/runtime
- @babel/traverse
- @babel/types
- @builder.io/partytown
- @gatsbyjs/reach-router
- @gatsbyjs/webpack-hot-middleware
- @graphql-codegen/add
- @graphql-codegen/core
- @graphql-codegen/plugin-helpers
- @graphql-codegen/typescript
- @graphql-codegen/typescript-operations
- @graphql-tools/code-file-loader
- @graphql-tools/load
- @jridgewell/trace-mapping
- @nodelib/fs.walk
- @parcel/cache
- @parcel/core
- @pmmmwh/react-refresh-webpack-plugin
- @sigmacomputing/babel-plugin-lodash
- @types/http-proxy
- @typescript-eslint/eslint-plugin
- @typescript-eslint/parser
- @vercel/webpack-asset-relocator-loader
- acorn-loose
- acorn-walk
- address
- anser
- autoprefixer
- axios
- babel-jsx-utils
- babel-loader
- babel-plugin-add-module-exports
- babel-plugin-dynamic-import-node
- babel-plugin-remove-graphql-queries
- babel-preset-gatsby
- better-opn
- bluebird
- body-parser
- browserslist
- cache-manager
- chalk
- chokidar
- common-tags
- compression
- cookie
- core-js
- cors
- css-loader
- css-minimizer-webpack-plugin
- css.escape
- date-fns
- debug
- deepmerge
- detect-port
- devcert
- dotenv
- enhanced-resolve
- error-stack-parser
- eslint
- eslint-config-react-app
- eslint-plugin-flowtype
- eslint-plugin-import
- eslint-plugin-jsx-a11y
- eslint-plugin-react
- eslint-plugin-react-hooks
- eslint-webpack-plugin
- event-source-polyfill
- execa
- express
- express-http-proxy
- fastest-levenshtein
- fastq
- file-loader
- find-cache-dir
- fs-exists-cached
- fs-extra
- gatsby-cli
- gatsby-core-utils
- gatsby-graphiql-explorer
- gatsby-legacy-polyfills
- gatsby-link
- gatsby-page-utils
- gatsby-parcel-config
- gatsby-plugin-page-creator
- gatsby-plugin-typescript
- gatsby-plugin-utils
- gatsby-react-router-scroll
- gatsby-script
- gatsby-sharp
- gatsby-worker
- glob
- globby
- got
- graphql
- graphql-compose
- graphql-http
- graphql-tag
- hasha
- invariant
- is-relative
- is-relative-url
- joi
- json-loader
- latest-version
- linkfs
- lmdb
- lodash
- meant
- memoizee
- micromatch
- mime
- mini-css-extract-plugin
- mitt
- moment
- multer
- node-fetch
- node-html-parser
- normalize-path
- null-loader
- opentracing
- p-defer
- parseurl
- path-to-regexp
- physical-cpu-count
- platform
- postcss
- postcss-flexbugs-fixes
- postcss-loader
- prompts
- prop-types
- query-string
- raw-loader
- react-dev-utils
- react-refresh
- react-server-dom-webpack
- redux
- redux-thunk
- resolve-from
- semver
- shallow-compare
- signal-exit
- slugify
- socket.io
- socket.io-client
- stack-trace
- string-similarity
- strip-ansi
- style-loader
- style-to-object
- terser-webpack-plugin
- tmp
- true-case-path
- type-of
- url-loader
- uuid
- webpack
- webpack-dev-middleware
- webpack-merge
- webpack-stats-plugin
- webpack-virtual-modules
- xstate
- yaml-loader
Dev Dependencies (31)
- @babel/cli
- @babel/helper-plugin-utils
- @babel/register
- @testing-library/jest-dom
- @testing-library/react
- @types/babel-core
- @types/eslint
- @types/estree
- @types/express
- @types/express-http-proxy
- @types/micromatch
- @types/normalize-path
- @types/reach__router
- @types/react-dom
- @types/semver
- @types/signal-exit
- @types/string-similarity
- @types/tmp
- @types/webpack-virtual-modules
- babel-preset-gatsby-package
- copyfiles
- cross-env
- documentation
- react
- react-dom
- rimraf
- typescript
- xhr-mock
- zipkin
- zipkin-javascript-opentracing
- zipkin-transport-http
Peer Dependencies (2)
Badge
To add a badge like this oneto your package's README, use the codes available below.
You may also use Shields.io to create a custom badge linking to https://www.jsdocs.io/package/gatsby
.
- Markdown[](https://www.jsdocs.io/package/gatsby)
- HTML<a href="https://www.jsdocs.io/package/gatsby"><img src="https://img.shields.io/badge/jsDocs.io-reference-blue" alt="jsDocs.io"></a>
- Updated .
Package analyzed in 10255 ms. - Missing or incorrect documentation? Open an issue for this package.