⚡ TL;DR
Use Storyblok CLI and emeraldwalk.runonsave to automate TypeScript type generation for Storyblok components.
Find the full source code here: Storyblok TypeScript Types Generator
If you're using Storyblok with TypeScript, ensuring type safety can significantly enhance your development experience. Instead of manually defining types, you can automatically generate TypeScript types from your Storyblok component schema. This tutorial will guide you through setting up a Storyblok TypeScript types generation.
📦 Setting Up the Type Generator
1. Install Dependencies
First, ensure that you have Node.js v20+ installed. Then, install the necessary packages:
npm i -D storyblok
2. Authenticate with Storyblok
You'll need to log in to Storyblok CLI to fetch your component schemas. Run the following command:
npx storyblok login
3. Configure Your Space ID
Create a .env.local
file in your project root and add your Storyblok Space ID:
STORYBLOK_SPACE_ID=your_space_id_here
4. Create the Type Generation Script
If you haven't cloned the repository, create a new script file to generate Storyblok types. Inside your project, create a directory called scripts/
and a file named storyblok.sh
:
mkdir -p scripts && touch scripts/storyblok.sh
Then, open scripts/storyblok.sh
and add the following content:
Let's break down what this script does:
- Loads the Storyblok Space ID from
.env.local
- Pulls component schemas from Storyblok and saves them to
__storyblok__/components.schema.json
- Runs
storyblok generate-typescript-typedefs
to generate TypeScript types insidetypes/storyblok.d.ts
Make sure the script is executable:
chmod +x scripts/storyblok.sh
Then, add a corresponding script in package.json
:
{
"scripts": {
"storyblok:types": "bash scripts/storyblok.sh"
}
}
⚡ Generating TypeScript Types
To manually generate TypeScript types, execute:
npm run storyblok:types
This will:
- Fetch components from Storyblok
- Save them to
__storyblok__/components.schema.json
- Generate TypeScript types inside
types/storyblok.d.ts
🏗 Automating Type Updates with VS Code
You can automate type generation every time you update your Storyblok schema. But there's a catch—it won’t just work out of the box. You’ll need to install the emeraldwalk.runonsave VS Code extension and configure it.
1. Install the Extension
Install emeraldwalk.runonsave from the VS Code marketplace.
2. Configure settings.json
Add the following configuration to your VS Code settings.json
file:
{
"emeraldwalk.runonsave": {
"shell": "/bin/bash",
"commands": [
{
"match": "__storyblok__/.*\\.json$",
"cmd": "bash scripts/storyblok.sh"
}
]
}
}
This setup ensures that whenever a .json
file inside __storyblok__/
is saved, the storyblok.sh
script runs automatically, keeping your TypeScript definitions up to date.
✅ Conclusion
And that's it! With just a little setup, you now have fully automated TypeScript types for your Storyblok components. No more manual type definitions—just clean, reliable, and always up-to-date types.