Setting up Storybook with Tailwindcss, ReactJS and Typescript: A comprehensive guide

What is the best way to configure Storybook to handle Tailwindcss styles and absolute paths?

Just a heads up, this question and answer are self-documenting in line with this. It was quite the process to figure out, but I'm certain it will help others facing the same issue.

Answer №1

When working with paths in Storybook, we utilize tsconfig as our reference point. Assuming you already have a ReactJS project set up with the typescript template.

Configuring Absolute Paths

1. Setting absolute paths in typescript

To define your absolute paths, add them under "paths" in tsconfig.js.

// tsconfig.json

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

2. Extending tsconfig absolute paths for Storybook

Install the tsconfig-paths-webpack-plugin from npm. It's widely used with millions of weekly downloads.

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

In .storybook/main.js, enhance the path resolution using the following code in your module.exports.

// .storybook/main.js

const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');

module.exports = {
  // Include this block of code in addition to existing configurations
  "webpackFinal": async (config) => {
    config.resolve.plugins = [
      ...(config.resolve.plugins || []),
      new TsconfigPathsPlugin({
        extensions: config.resolve.extensions,
      }),
    ];
    return config;
  },
};

Source

3. Styling Tailwind CSS in Storybook

Add these two lines 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 now be styled correctly.

Additional considerations

If using Tailwind v3+, ensure your tailwind.config.js doesn't include purge options or explicitly mentions JIT. Here's an example configuration:

// tailwind.config.js

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The Excel Match function is experiencing issues when used in conjunction with the MS-Graph API

Recently, I've encountered an issue with sending a match-function post request to an Excel workbook using the MS-Graph API. Instead of receiving the value of the first column that contains the lookup value, I'm getting the value from the second c ...

Creating an Excel file with a right-to-left sheet column order using React: A step-by-step guide

The code provided above is functioning properly and successfully generates the file file.xlsx. Inquiry: Is there a way to arrange the columns of the sheets in right-to-left order? import React from 'react' import * as FileSaver from "file-s ...

Can you specify a default value in react-select using ReactJS?

After extensive research on the issue, I have been unable to find a solution. I am trying to display a specific value by default in the select box in the view. This is my select code: <Select options={getMainCategory.data.map((item) => { ...

Refactor the fat arrow function in Typescript to maintain the bare function signature verification

When using AOT in Angular, it is necessary to rewrite all functions and reducers to not utilize arrow functions: An error occurred: Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function o ...

React hooks - Issue with updating state properties within sidebar display

When resizing the window, I have an event that will display either the desktop sidebar or the mobile sidebar. However, there are variables that are not immediately updated to show the sidebar correctly based on the window size. In a desktop window, this ca ...

What is the best way to position my two icons next to each other in the footer of my React application?

I'm struggling with styling the footer of my react portfolio project. I specifically want to include Github and LinkedIn icons side-by-side at the bottom of the screen, but currently, they are stacked vertically in the middle of the page with too much ...

Struggling to modify the datetimepicker material-ui within a react js class component

I am currently using a datetimepicker component from material-ui/pickers in a class-based react-js component. I am facing an issue where the datetimepicker closes immediately every time I click on any part of it (date, year, etc.). Here's a snippet of ...

Before the service call finishes, Akita queries this.selectAll and returns an empty list

Here is the code snippet from my file named widgetquery.ts: @Injectable({ providedIn: 'root' }) export class WidgetQuery extends QueryEntity<WidgetState, WidgetTO> { public Widget$: Observable<WidgetTO> = this.selectActive().filter( ...

Centering form fields in ReactJS using Material UI

I'm currently facing a challenge trying to center-align my react form. Below is the structure of my form: The technology I am using is Material UI for ReactJS <Grid item xs={12}> <Grid item xs={12}> <FormGroup ...

Is there a way to display a customized label in getOptionLabel method similar to renderOption in Material UI Autocomplete?

I have a requirement to display the total number of items in each option for the Autocomplete feature. While I am able to show this in expanded items, I am unable to display it when one is selected. Please refer to the image and code provided and suggest ...

Discover the combined type of values from a const enum in Typescript

Within my project, some forms are specified by the backend as a JSON object and then processed in a module of the application. The field type is determined by a specific attribute (fieldType) included for each field; all other options vary based on this ty ...

Trouble accessing setState within an axios call in ReactJs

I've encountered an issue while attempting to set the state of the variable isCorrectAnswer within an axios call. The error message Cannot read properties of undefined (reading 'setState') is showing up in the console log. What mistake am I ...

Retrieve various data types through a function's optional parameter using TypeScript

Creating a custom usePromise function I have a requirement to create my own usePromise implementation. // if with filterKey(e.g `K=list`), fileNodes's type should be `FileNode` (i.e. T[K]) const [fileNodes, isOk] = usePromise( () => { ...

Tips for leveraging the functions service in Next.js for better code reusability

I am just starting to learn Next.js and I have a preference for organizing my API functions in a separate folder called services. I attempted to implement some code based on this topic but unfortunately, it did not work as expected. It seems like my api fu ...

Experience the visually stunning React Charts line chart featuring grouped labels such as months and weeks

Can you create a line chart in recharts with grouped points, such as displaying 6 months data series per day for about 180 days? Each point on the chart represents a day, but I want the X-axis labels to show the corresponding month like Jan, Feb, Mar, Apr, ...

What is the best way to display a message on the 403 client side when an email sending fails?

I am attempting to display an alert message when the email is sent successfully or if it fails. If it fails, I receive a 403 status code from the backend. However, I am unsure how to handle this error on the client-side. In the case of success, I receive a ...

Order of execution for Angular 2 components

import { Component, OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms'; import {Router, ActivatedRoute, Params} from '@angular/router'; import { Country } from &ap ...

How can we retrieve the initial data of components in the _app.js page?

My website's navigation bar relies on dynamic data fetched from an API using the getStaticProps method. Since I want the navigation bar to be displayed on all pages, placing it in the _app.js component seems like the best option. However, the issue is ...

Grid vs Container: Deciding Between the Two - Material-UI

Here's a question I've been pondering lately: Box and Grid are both layout components designed for adding other components inside them. However, I often find that sometimes Box works best for me, while other times it's Grid. And occasionall ...

Avoid unnecessary re-renders in React Redux by ensuring that components do not update when properties are not utilized in their

I'm encountering an issue with a component that keeps re-rendering. I've implemented Redux to handle my states. Within a component, I access a property (isPlaying: bool) from the state using mapStateToProps in various methods of the component, ex ...