Search code examples
reactjstypescripttailwind-cssstorybook

How to setup Storybook with Tailwindcss, ReactJS and Typescript


How do you setup Storybook so that it parses Tailwindcss styles and also parses absolute paths?

Note: This is a self-documenting question/answer allowed as per this. This took a while to figure out and I'm sure many others will encounter this.


Solution

  • To resolve paths in Storybook, we'll be using tsconfig as the source. We assume you have installed a ReactJS project with the typescript template already.

    Setting Absolute Paths

    1. Define absolute paths in typescript

    Add your absolute paths under "paths" in tsconfig.js.

    // tsconfig.json
    
    {
      "compilerOptions": {
        // ...
        "baseUrl": "src",
        "paths": {
          "#assets/*": ["./assets/*"],
          "#components/*": ["./components/*"],
          // etc.
        }
      }
      "include": ["src"]
    }
    

    2. Extend the tsconfig absolute paths to work in Storybook

    Install the tsconfig-paths-webpack-plugin from npm. Has millions of weekly downloads at time of writing.

    $ npm install -D tsconfig-paths-webpack-plugin
    // or
    $ yarn add -D tsconfig-paths-webpack-plugin
    

    Under .storybook/main.js extend the tsconfig path resolution by adding the following to your module.exports.

    // .storybook/main.js
    
    const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
    
    module.exports = {
      // Add the following block of code in addition to what's existing
      "webpackFinal": async (config) => {
        config.resolve.plugins = [
          ...(config.resolve.plugins || []),
          new TsconfigPathsPlugin({
            extensions: config.resolve.extensions,
          }),
        ];
        return config;
      },
    };
    

    Source

    3. Parsing Tailwind Styles in Storybook

    Add the following two lines of code at the top of your .storybook/preview.js file.

    // .storybook/preview.js
    
    import '!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css';
    import 'tailwindcss/tailwind.css';
    

    Source

    Your tailwindcss should parse now.

    Additional files

    For Tailwind v3+, make sure your tailwind.config.js doesn't have the purge option and doesn't explicitly state JIT. Mine looks like this:

    // tailwind.config.js
    
    module.exports = {
        content: [
            "./src/**/*.{js,jsx,ts,tsx}"
        ],
        theme: {
            extend: {},
        },
        plugins: [],
    };