prismic-ts-codegen - v1

Overview

prismic-ts-codegen is a command line tool for generating TypeScript types that match your Prismic repository’s content.

To fully type your queries, it can automatically integrate with @prismicio/client, the primary package used to query content from a Prismic repository.

Dependencies and requirements

prismic-ts-codegen can be used in any JavaScript or TypeScript project that uses @prismicio/client or Prismic’s Rest API V2. It integrates nicely into projects that are built with Slice Machine, but Slice Machine is not required.

prismic-ts-codegen relies on @prismicio/types as a peer dependency.

If the automatic @prismicio/client integration is enabled (it is enabled by default), @prismicio/client is also required.

Installation

Install packages

Add prismic-ts-codegen and its peer dependencies to your Prismic project via the command line:

Copy
npm install --save-dev prismic-ts-codegen @prismicio/types

Create configuration file

Create a prismicCodegen.config.ts configuration file at the root of your project via the command line:

Copy
npx prismic-ts-codegen init

Configure your model locations

Models can be loaded locally from files in your project, or they can be loaded remotely from the Custom Types API.

To load local model files from your project, add the paths to all of your custom type and Slice model files in your prismicCodegen.config.ts file. If your project uses Slice Machine, this line should already be filled in.

prismicCodegen.config.ts
Copy
  import type { Config } from 'prismic-ts-codegen'

  const config: Config = {
    output: './types.generated.ts',
   models: ['./customtypes/**/index.json', './slices/**/model.json'],
  }

  export default config

If the Prismic repository’s models are not stored in your project, see the Loading remote models with the Custom Types API section below.

Usage

Generating types

You can generate TypeScript types based on your custom type and Slice models with the following command:

Copy
npx prismic-ts-codegen

This will load your models, convert them to TypeScript types, and save them to a TypeScript file in your project. By default, the output is saved to types.generated.ts.

Any time you edit your models, run the command again to regenerate the types.

That's it!

For most projects, this is as far as you need to go thanks to the automatic @prismicio/client integration. The generated types will automatically be integrated into your Prismic client.

The output file location can be configured using prismicCodegen.config.ts's output property.

prismicCodegen.config.ts
Copy
  import type { Config } from 'prismic-ts-codegen'

  const config: Config = {
   output: './my-custom-file.ts',
    models: ['./customtypes/**/index.json', './slices/**/model.json'],
  }

  export default config

Automatic @prismicio/client integration

By default, prismic-ts-codegen generates code that automatically integrates your document types into @prismicio/client.

Copy
import * as prismic from '@prismicio/client'

const client = prismic.createClient('your-repo-name')
//    ^ Automatically contains references to document types

The return value of query methods specific to a single kind of document, such as getByUID(), will be typed with that kind of document.

Copy
const home = await client.getByUID('page', 'home')
//    ^ Typed as PageDocument

The return value of other query methods will be typed using a union of all generated document types, allowing you to narrow the type in your own code.

Copy
const drinks = await client.getByTag('drinks')
//    ^ Typed as PageDocument | MenuItemDocument | SettingsDocument

Further Learning: TypeScript with @prismicio/client

To learn more about using TypeScript with @prismicio/client, see the TypeScript section of the @prismicio/client Technical Reference.

You can disable the automatic @prismicio/client integration in prismicCodegen.config.ts:

prismicCodegen.config.ts
Copy
  import type { Config } from 'prismic-ts-codegen'

  const config: Config = {
    output: './types.generated.ts',
    models: ['./customtypes/**/index.json', './slices/**/model.json'],
   clientIntegration: {
     includeCreateClientInterface: false,
   },
  }

  export default config

Generated types

The following TypeScript types are exported from the generated file.

AllDocumentTypes: A union of all Prismic document types. This type is useful when manually providing types to @prismicio/client.

Copy
export type AllDocumentTypes =
  | ArticleDocument
  | NavigationDocument
  | PageDocument
  | SettingsDocument

Documents: Exported as ${name}Document types, where ${name} is the Pascal cased document ID.

Copy
// Simplified example

export type BlogPostDocument = PrismicDocumentWithUID<
  BlogPostDocumentData,
  'blog_post'
>

Slices: Exported as ${name}Slice, where ${name} is the Pascal cased Slice ID. If the Slice was created using the Legacy Builder (i.e. not created with Slice Machine), the name will be fully qualified, including its custom type ID.

Copy
// Simplified example

export type ImageSlice = SharedSlice<'image', ImageSliceVariation>

Slice variations: Exported as ${name}Slice${variationName}, where ${name} is the Pascal cased Slice ID, and ${variationName} is the Pascal cased variation ID.

Copy
// Simplified example

export type ImageSliceWide = SharedSliceVariation<
  'wide',
  ImageSliceWidePrimary,
  ImageSliceWideItem
>

Slice items and group field items: Exported as ${name}Item, where ${name} is the fully qualified name of the field, including its Slice ID or custom type ID.

Copy
// Simplified example

export interface NavigationDocumentDataLinksItem {
  label: KeyTextField
  link: LinkField
}

Loading remote models with the Custom Types API

prismic-ts-codegen can be configured to load custom type and Slice models remotely using Prismic’s Custom Types API. This option is helpful if you are working on a project that queries content from a Prismic repository but does not manage its custom types or Slices.

To load models from the Custom Types API:

  1. Add your Prismic repository name to prismicCodegen.config.ts.
  2. Generate a Custom Types API token and add it to the configuration file.
  3. Enable fetching models from your Prismic repository.
prismicCodegen.config.ts
Copy
  import type { Config } from 'prismic-ts-codegen'
 import dotenv from 'dotenv'

 dotenv.config({ path: '.env' })

  const config: Config = {
    output: './types.generated.ts',
   repositoryName: 'your-repo-name',
   customTypesAPIToken: process.env.PRISMIC_CUSTOM_TYPES_API_TOKEN,
   models: {
     fetchFromRepository: true,
   },
  }

  export default config

Storing your Custom Types API token in an uncommitted .env file is highly recommended over storing it directly in the prismicCodegen.config.ts file. In the example above, this is accomplished using the dotenv package and accessing the token using process.env.

Copy
# To install dotenv
npm install --save-dev dotenv
.env
Copy
PRISMIC_CUSTOM_TYPES_API_TOKEN=your-token

To load models both locally and remotely, provide a list of local files to the files property within the models object:

prismicCodegen.config.ts
Copy
  import type { Config } from 'prismic-ts-codegen'

  const config: Config = {
    output: './types.generated.ts',
    repositoryName: 'your-repo-name',
    customTypesAPIToken: 'your-custom-types-api-token',
    models: {
     files: ['./customtypes/**/index.json', './slices/**/model.json'],
      fetchFromRepository: true,
    },
  }

  export default config

Local models take priority over ones fetched remotely.

Contributing

Whether you're helping us fix bugs, improve the docs, or spread the word, we'd love to have you as part of the Prismic developer community!

Asking a questionOpen a new topic on our community forum explaining what you want to achieve / your question. Our support team will get back to you shortly.

Reporting a bugOpen an issue on GitHub explaining your application's setup and the bug you're encountering.

Suggesting an improvementOpen an issue on GitHub explaining your improvement or feature so we can discuss and learn more.

Submitting code changes: For small fixes, feel free to open a pull request with a description of your changes. For large changes, please first open an issue so we can discuss if and how the changes should be implemented.

For more clarity on prismic-ts-codegen and its structure, you can also check out the detailed Contributing document on GitHub.


Was this article helpful?
Not really
Yes, Thanks

Can't find what you're looking for? Spot an error in the documentation? Get in touch with us on our Community Forum or using the feedback form above.