Skip to content

Solution for using Storybook with TypeScript #426

@xogeny

Description

@xogeny

I'm following the StackOverflow tradition of asking a question and then answering it.

The question is:

"how can I use @kadira/storybook with TypeScript?"

It turns out, you can pretty much follow the Slow Start Guide and things will largely work. But there are a few tweaks. The first is that you should point your config.js file (I don't bother using TS here) at your stories written in TypeScript, e.g.,

import { configure } from '@kadira/storybook';

function loadStories() {
    console.log("Loading stories");
    require('../stories/visuals.tsx');
    // You can require as many stories as you need.
}

configure(loadStories, module);

Note the .tsx suffix there. Now the other part of making this work is recognizing that storybook is using webpack under the hood (and v1 at that).

The really nice thing with storybook is that the recognize that you will likely need to customize the webpack.config.js configuration and they make that relatively easy to do. Initially, I tried to include my own webpack.config.js, but that interferes with the storybook machinery. So instead, what I found worked quite well was to simply use the extension mechanisms already documented for storybook. This led me to this (assuming you have ts-loader and typescript as dev dependencies):

// load the default config generator.
var genDefaultConfig = require('@kadira/storybook/dist/server/config/defaults/webpack.config.js');

module.exports = function (config, env) {
    var config = genDefaultConfig(config, env);

    config.module.loaders.push({
        test: /\.tsx$/,
        loader: 'ts-loader'
    })
    config.module.loaders.push({
        test: /\.ts$/,
        loader: 'ts-loader'
    })
    config.resolve.extensions.push(".tsx");
    config.resolve.extensions.push(".ts");

    return config;
};

As you can see, this is just boilerplate. It doesn't refer to any of my project's files or settings so you can pretty much use it as is. Just drop it in as .storybook/webpack.config.js in your project and you should be good to go.

The important thing to understand here is that by using storybook, webpack and ts-loader you are going to get hot module reloading of your TypeScript code for free, which is very sweet.

Hopefully people will find this useful.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions