Configuring Sanity TypeGen for multiple-folder projects
Before you can generate types for GROQ query results, you must add some configuration that tells the TypeGen tooling where to look for those queries and where to put the file with the generated types.
Before diving in, it’s important to remember that you are still dependent on the schema.json file to generate types for your front end. You should also keep in mind that every time you change the Studio’s schema, you will have to rerun the extraction, and every time you change a GROQ query, you should update your types as well.
sanity.cli.ts file in your Studio folder. You'll also need schemaExtraction.enabled: true to generate the schema.json file that typegen uses.import {defineCliConfig} from 'sanity/cli'
export default defineCliConfig({ api: { projectId: 'your-project-id', dataset: 'production' }, schemaExtraction: { enabled: true, }, typegen: { path: '../day-one-with-sanity-nextjs/src/**/*.{ts,tsx,js,jsx}', schema: 'schema.json', generates: '../day-one-with-sanity-nextjs/src/sanity/types.ts' }})All TypeGen configuration lives in sanity.cli.ts. If you have an older project with a separate sanity-typegen.json file, move that configuration here — the JSON file is deprecated.
The configuration works like this:
pathconfigures where and which files Sanity TypeGen looks for GROQ queries. In this case, it will look through all the files in the front end’ssrcfolderschemais where to find the static schema representation. The default value isschema.json.generatessets the path and the file name with the generated TypeScript definitions, in this case, in the front end’ssanityfolder
schemaExtraction.enabled: true generates the schema.json file automatically during sanity dev and sanity build. If you also want to generate types in the studio itself (for custom components, etc.), add typegen.enabled: true as well. This is covered in the Generating types lesson.With this configuration file in place, you can now run the typegen command:
npx sanity typegen generateIf run successfully, you’ll see the result like this:
✔ Generated TypeScript types for 14 schema types and 0 GROQ queries in 0 files into: ../day-one-with-sanity-nextjs/src/sanity/types.tstypes.ts file in your Next.js project folder and inspect its contentNotice how it says “0 GROQ queries,” this means you have to tweak your front end code to let Sanity TypeGen find your queries as well.