使用脚本在编译时获取组件的 Zod 描述
此功能允许你以类型安全的 “Zod” 描述形式获取架构描述,为你的架构提供以 TypeScript 为优先的模式验证和静态类型推断。
为了拉取我们的 Zod 模式,我们将加载一些依赖,并创建一个脚本来使用 cms-renderer 中的一些实用工具。
让我们先来看项目结构
theme={null}
apps/
web/
app/
page.tsx
scripts/
generated-schema.ts // 这是脚本所在的位置
现在我们来编辑这个 generated-schema.ts 文件
generated-schema.ts theme={null}
import { fetchAllCustomSchemaFields, saveZodSchemaCode } from 'cms-renderer/lib/custom-schemas';
import { cmsConfig } from '../lib/cms-config'; // 导入我的配置
async function main() {
const { cmsUrl, websiteId } = cmsConfig;
if (!cmsUrl) {
throw new Error(
'[generate-schemas] NEXT_PUBLIC_CMS_API_URL 未设置。请在你的环境变量或 .env 文件中进行设置。'
);
}
if (!websiteId) {
throw new Error(
'[generate-schemas] CMS_WEBSITE_ID 未设置。请在你的环境变量或 .env 文件中进行设置。'
);
}
await saveZodSchemaCode(
await fetchAllCustomSchemaFields(cmsConfig),
'./generated/cms-schemas.ts'
);
console.log('[generate-schemas] 完成。');
}
main().catch((err) => {
console.error('[generate-schemas] 失败:', err);
process.exit(1);
});
你的 CmsConfig 应该如下所示
theme={null}
export const cmsConfig = {
cmsUrl: process.env.NEXT_PUBLIC_CMS_API_URL,
apiKey: process.env.CMS_API_KEY,
websiteId: '...',
};
在我们的 package.json 中,我们定义了如何运行脚本以及相关依赖。
注意:如果你没有 tsconfig,那么可以移除 --tsconfig 标志及其值。
package.json theme={null}
{
"name": "web",
"version": "0.1.0",
"type": "module",
"private": true,
"scripts": {
"generate-schemas": "tsx --tsconfig tsconfig.json scripts/generate-schemas.ts",
"...": "..."
},
现在,当我们运行
$ bun run generate-schemas
tsx --tsconfig tsconfig.json scripts/generate-schemas.ts
[generate-schemas] 完成。
我们应该会得到类似的输出,并且可以在项目结构中看到一个新文件
theme={null}
apps/
web/
app/
page.tsx
scripts/
generated-schema.ts // 这是脚本所在的位置
generated/
cms-schema.ts // 生成的 Zod 模式
你可以打开查看其中内容,了解你的模式是什么样子。要更新这个文件,你需要再次运行 bun run generate-schemas 命令,你可以将其连接到 dev 或 build 工作流中。
然后我们可以在 page.tsx 文件中像这样引入这些 Zod 对象
page.tsx theme={null}
import type { PetFoodPost, SiteConfig } from '@/generated/cms-schemas';
import { petFoodPostSchema } from '@/generated/cms-schemas';
// 调用 petFoodPostSchema.parse(obj) 以对对象进行类型安全的解析
你可以在管理面板中更新你的模式,并再次拉取更新后的模式,以便于开发。