如何通过代码配置Strapi的数据类型与集合类型?
如何通过代码配置Strapi的数据类型与集合类型?
嗨,我完全懂你不想每次新建Strapi项目都手动折腾Post、Product这些集合类型,也不想靠复制data.db这种不够优雅的方式。其实Strapi本身就支持通过代码程序化创建内容类型,下面给你一套实用的落地方案:
一、编写自定义配置脚本
我们可以写一个TypeScript脚本,直接调用Strapi内部的Content Type Builder服务来批量创建集合类型,步骤如下:
- 在项目根目录新建
scripts文件夹,里面创建setup-content-types.ts文件,内容如下:
import { Strapi } from '@strapi/strapi'; async function setupContentTypes() { // 初始化Strapi实例(需确保dist目录存在,所以先启动过一次项目) const strapi = await Strapi({ distDir: './dist' }).load(); // 定义Post集合类型的完整配置 const postConfig = { kind: 'collectionType', collectionName: 'posts', info: { name: 'Post', description: '博客文章类型', }, options: { draftAndPublish: true, // 开启草稿/发布功能 }, attributes: { title: { type: 'string', required: true, }, content: { type: 'richtext', required: true, }, cover: { type: 'media', allowedTypes: ['images'], multiple: false, }, publishedAt: { type: 'datetime', }, }, }; // 定义Product集合类型的完整配置 const productConfig = { kind: 'collectionType', collectionName: 'products', info: { name: 'Product', description: '电商产品类型', }, options: { draftAndPublish: true, }, attributes: { name: { type: 'string', required: true, }, price: { type: 'decimal', required: true, min: 0, }, stock: { type: 'integer', default: 0, }, description: { type: 'text', }, }, }; try { // 调用服务创建Post类型 await strapi.plugin('content-type-builder').service('content-types').create(postConfig); console.log('✅ Post集合类型创建成功'); // 创建Product类型 await strapi.plugin('content-type-builder').service('content-types').create(productConfig); console.log('✅ Product集合类型创建成功'); // 重新加载Strapi以应用新配置 await strapi.reload(); console.log('🔄 Strapi已重新加载,新类型生效'); } catch (err) { console.error('❌ 创建内容类型失败:', err); process.exit(1); } finally { // 销毁实例避免内存泄漏 await strapi.destroy(); } } // 执行脚本 setupContentTypes();
- 安装依赖:因为用了TypeScript,需要安装
ts-node直接运行TS脚本:
yarn add ts-node --dev
- 在
package.json里添加运行脚本:
{ "scripts": { "setup:types": "ts-node scripts/setup-content-types.ts" } }
二、脚本使用流程
每次新建项目后,按以下步骤操作:
- 先启动一次Strapi:
yarn develop,等它生成好dist等必要目录后,按Ctrl+C停止服务 - 运行配置脚本:
yarn setup:types - 再次启动Strapi:
yarn develop,就能在后台看到Post和Product这两个集合类型了
三、额外技巧与注意事项
- 配置复用:可以把Post、Product的配置抽成单独的JSON文件(比如
config/post-type.json),然后在脚本里导入,方便后续修改和扩展 - 复杂字段支持:如果需要关联类型、组件、本地化等,只需要在
attributes里添加对应配置即可,格式和你在Strapi后台手动创建时的Schema完全一致 - 模板替代方案:如果希望一步到位创建带预设类型的项目,可以制作Strapi模板项目(把配置好的内容类型存在项目里),然后用
yarn create strapi-app my-project --template ./path-to-your-template直接创建,适合团队统一复用
这样就完全摆脱了手动创建或复制数据库的方式,全程用代码控制,非常适合自动化部署和项目初始化场景。
备注:内容来源于stack exchange,提问作者Kristi Jorgji
相关产品推荐
相关产品推荐

