prismic-ts-codegen

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:

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:

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
  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:

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.

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

prismicCodegen.config.ts
  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.

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.

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.

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

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

prismicCodegen.config.ts
  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.

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

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

// 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.

// 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.

// 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.

// 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:

  • Add your Prismic repository name to prismicCodegen.config.ts.
  • Generate a Custom Types API token and add it to the configuration file.
  • Enable fetching models from your Prismic repository.
prismicCodegen.config.ts
  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.

# To install dotenv
npm install --save-dev dotenv
.env
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
  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 question: Open 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 bug: Open an issue on GitHub explaining your application’s setup and the bug you’re encountering.

Suggesting an improvement: Open 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.