MicroCMS TypeScript Type Generator
The `microcms-typescript` package is a command-line interface (CLI) tool designed to generate TypeScript type definitions directly from MicroCMS API schema JSON files. Currently stable at version 1.0.15, this utility provides a bridge between your MicroCMS content models and your TypeScript codebase, enabling strong type-safety for your MicroCMS data. Unlike the `microcms-js-sdk` or `microcms-ts-sdk` which are client libraries for interacting with the MicroCMS API, `microcms-typescript` focuses solely on code generation. It processes local JSON files representing MicroCMS API schemas and outputs corresponding TypeScript `type` declarations, including a comprehensive `EndPoints` type that encapsulates `gets`, `get`, `post`, `put`, and `patch` operations, ensuring type-safe access to your content structure. This distinction is crucial as it targets the build-time generation of types rather than runtime API interaction.
Common errors
-
Error: Cannot find module 'microcms-typescript' or its corresponding type declarations.
cause Attempting to `import` the `microcms-typescript` package into application code. It is a command-line interface (CLI) tool, not a library meant for direct import.fixDo not import `microcms-typescript` into your code. Instead, run it as a CLI command using `npx microcms-typescript` or, if installed globally, `microcms-typescript`. -
Error: ENOENT: no such file or directory, stat '<src-dir>'
cause The source directory (`src-dir`) provided to the CLI tool does not exist or is inaccessible. This typically means the path to your MicroCMS schema JSON files is incorrect.fixVerify that the `src-dir` argument points to an existing directory containing your MicroCMS schema JSON files. Ensure correct casing and full path if running from a different working directory. -
Error: Failed to parse schema file: <path/to/schema.json>
cause One of the MicroCMS schema JSON files in the `src-dir` is malformed (e.g., invalid JSON syntax) or its structure does not conform to the expected MicroCMS schema format.fixInspect the specified JSON file (`<path/to/schema.json>`) for syntax errors. Validate its content against the expected MicroCMS API schema structure. -
Property 'contents' does not exist on type 'EndPoints["gets"]["your-api-name"]'.
cause The generated types are outdated or the API name used in the `EndPoints` type access doesn't match the actual API endpoint name in your MicroCMS schema files.fixFirst, ensure your MicroCMS schema JSON files are up-to-date and reflect your current API structure. Then, re-run the `microcms-typescript` CLI to regenerate `cms-types.ts`. Double-check the API name used (e.g., 'blogs') matches the filename of your schema JSON (e.g., `api-blogs-schema.json`).
Warnings
- gotcha The functionality of `microcms-typescript` relies on the stability of MicroCMS's schema export format. Significant changes to how MicroCMS structures its exported JSON schemas could lead to incorrect type generation or runtime errors until the tool is updated.
- gotcha The `microcms-typescript` CLI tool will overwrite the specified `dist-file` (e.g., `cms-types.ts`) if it already exists. Ensure that this file is either exclusively generated or that its contents are not manually edited, as changes will be lost on subsequent runs.
- gotcha When using `microcms-typescript` in a project with an older Node.js or TypeScript version, compatibility issues may arise. TypeScript itself has had breaking changes in recent major versions regarding Node.js requirements (e.g., TS 5.1+ requires Node 14.17+).
Install
-
npm install microcms-typescript -
yarn add microcms-typescript -
pnpm add microcms-typescript
Imports
- EndPoints
import type { EndPoints } from './cms-types'; - EndPoints['gets']['your-api-name']
let listData: EndPoints['gets']['blogs'];
- EndPoints['get']['your-api-name']
let detailData: EndPoints['get']['blogs'];
Quickstart
mkdir microcms-schemas
cat > microcms-schemas/api-blogs-schema.json <<EOF
{
"apiFields": [
{
"idValue": "blogTitleField",
"fieldId": "title",
"name": "Title",
"kind": "text",
"required": true,
"isUnique": false
},
{
"fieldId": "slug",
"name": "Slug",
"kind": "text",
"required": true,
"isUnique": true
},
{
"fieldId": "body",
"name": "Body",
"kind": "richEditor",
"required": true
},
{
"fieldId": "category",
"name": "Category",
"kind": "relation",
"required": false
}
],
"customFields": []
}
EOF
# Install the CLI tool
npm install microcms-typescript --save-dev
# Generate TypeScript types from your schema files
npx microcms-typescript microcms-schemas cms-types.ts
# Example TypeScript usage (e.g., in src/types.ts or similar)
// Make sure your tsconfig.json includes 'cms-types.ts'
/*
// tsconfig.json example:
// {
// "compilerOptions": {
// "target": "ES2020",
// "module": "ESNext",
// "moduleResolution": "Bundler",
// "strict": true,
// "esModuleInterop": true,
// "skipLibCheck": true,
// "forceConsistentCasingInFileNames": true,
// "types": ["node"],
// "outDir": "./dist",
// "rootDir": ".",
// "paths": { "@/*": ["./src/*"] }
// },
// "include": ["./src/**/*.ts", "./src/**/*.d.ts", "cms-types.ts"]
// }
*/
import type { EndPoints } from './cms-types';
// Type for a list of blog posts
type BlogListResponse = EndPoints['gets']['blogs'];
// Type for a single blog post's detail
type BlogDetail = EndPoints['get']['blogs'];
// Type for creating a new blog post (POST payload)
type BlogCreatePayload = EndPoints['post']['blogs'];
// Example usage with dummy data
const fetchedBlogs: BlogListResponse = {
contents: [
{
id: 'blog123',
title: 'My First Blog Post',
slug: 'my-first-blog-post',
body: '<p>Content here</p>',
createdAt: '2023-01-01T00:00:00.000Z',
updatedAt: '2023-01-01T00:00:00.000Z',
publishedAt: '2023-01-01T00:00:00.000Z',
revisedAt: '2023-01-01T00:00:00.000Z',
category: 'cat456'
}
],
totalCount: 1,
limit: 10,
offset: 0
};
console.log(fetchedBlogs.contents[0].title); // Accessing type-safe data