The following is a sub-package of sanity-codegen.
This package includes APIs to programmatically, execute, validate, normalize, and generate types from sanity.io schemas.
👋 NOTE: You don't have to use this package directly. It's only meant for users who want to use sanity-extractor programmatically. The CLI is the preferred way to use Sanity Codegen.
Installation
npm install --save-dev @sanity-codegen/extractor
or
yarn add --dev @sanity-codegen/extractor
Usage
Execute, validate, and normalize
The Sanity schemas are written for use inside of Sanity Studio. Sanity Studio is the primary client that writes data to Sanity's backend so all knowledge of the schema lives there.
This poses a challenge because the way we write schemas can become highly dependent on that environment (e.g. importing React components, CSS imports etc).
In order to pull out the schema types for codegen, Sanity Codegen provides a pre-configured babel setup that makes your schema executable in a Node context by shimming out the Studio environment (e.g. using css-modules-transform to ignore CSS imports). This execution occurs in a forked process to prevent and babel conflicts on the main thread.
After the schema has been loaded, it's then run through a validate/normalize step. This will validate that the schema makes sense and then normalize it. The normalized version is statically typed and JSON serializable and is sent over to the main thread.
const { schemaExtractor } = require('@sanity-codegen/extractor');
async function main() {
const normalizedSchema = await schemaExtractor({
sanityConfigPath: './studio/sanity.config.ts',
});
console.log(normalizedSchema);
}
Generate types
The normalized types can then be fed into generateTypes. This function takes in a normalized schema and returns a TypeScript source file.
const {
schemaExtractor,
generateSchemaTypes,
} = require('@sanity-codegen/extractor');
const fs = require('fs');
async function main() {
const normalizedSchema = await schemaExtractor({
sanityConfigPath: './studio/sanity.config.ts',
});
const typescriptSource = await generateSchemaTypes({ normalizedSchema });
await fs.promises.writeFile('./schema.d.ts', typescriptSource);
}
Reference
interface ExecutorOptions {
sanityConfigPath: string;
babelrcPath?: string;
babelOptions?: any;
cwd?: string;
}
export declare function schemaExtractor(
params: ExecutorOptions,
): Promise<Sanity.SchemaDef.Schema>;
See here for the definition of Sanity.SchemaDef.Schema
schemaNormalizer()
interface SchemaNormalizerOptions {
types: unknown[];
omitOriginalNode?: boolean;
}
export declare function schemaNormalizer(
options: SchemaNormalizerOptions,
): Sanity.SchemaDef.Schema;
defaultBabelOptions
export declare const defaultBabelOptions: BabelOptions;