DEV Community

Cover image for Setting up Storybook for Preact with TypeScript
Emma Goto 🍙
Emma Goto 🍙

Posted on • Originally published at emgoto.com on

Setting up Storybook for Preact with TypeScript

Storybook is a useful tool for visualising what your app's front-end components will look like across different scenarios.

This guide will cover how you can add Storybook to your TypeScript Preact app.

Creating a Preact app using TypeScript

If you don't already have a Preact app using TypeScript, you can easily create one using the preact-cli tool:

npm install -g preact-cli
preact create typescript app-name-here
Enter fullscreen mode Exit fullscreen mode

Remember to cd into your app's folder after you've created it!

Installing and setting up Storybook

Install Storybook for Preact:

npm install @storybook/preact --save-dev
Enter fullscreen mode Exit fullscreen mode

Then create a .storybook/main.js file, and add the following:

module.exports = {
    stories: ['../src/**/story.tsx'],
    webpackFinal: async config => {
        config.module.rules.push({
            test: /\.(ts|tsx)$/,
            use: [{
                loader: require.resolve('ts-loader'),
            }],
    });
    config.resolve.extensions.push('.ts', '.tsx');
    return config;
    },
};
Enter fullscreen mode Exit fullscreen mode

Note that you will have to modify the above code if you are not using ts-loader

Then you can add a new script to your package.json file:

"scripts": {
    "storybook": "start-storybook"
}
Enter fullscreen mode Exit fullscreen mode

(Optional) delete the declaration.d.ts file

If you created your app using the preact-cli tool, I found that deleting the declaration.d.ts file in your src folder was required to get Storybook working. I'm not too sure why, but give it a go if things are breaking for you.

Write your first story

Create a file called story.tsx and import in one of your components:

import { h } from 'preact';
import Component from './index';

export default { title: 'Component' }

export const coolComponent = () => <Component/>;
Enter fullscreen mode Exit fullscreen mode

Now if you run the command:

npm run storybook
Enter fullscreen mode Exit fullscreen mode

You will be able to see your storybooks in action.

Happy coding!

References

Storybook for Preact

Top comments (0)