Reputation: 510
I am trying to build my storybook with tailwind css. When running build-storybook
the components are rendered with the tailwind classes. Unfortunately, when I build storybook and run the create build storybook-static
with npx http-server storybook-static
the classes are not loaded into the stories and the components are displayed not styled.
This is a repro repo of my project: https://gitlab.com/ens.evelyn.development/storybook-issue
This is my main.js
:
const path = require('path')
module.exports = {
"stories": [
"../src/components/**/**/*.stories.mdx",
"../src/components/**/**/*.stories.@(js|jsx|ts|tsx)"
],
"addons": [
"@storybook/addon-links",
"@storybook/addon-essentials",
{
name: '@storybook/addon-postcss',
options: {
postcssLoaderOptions: {
implementation: require('postcss'),
},
},
},
"@storybook/addon-actions",
"storybook-tailwind-dark-mode"
]}
My Projectstructure looks like this:
.storybook
src
components
subdir
Button
index.tsx
button.stories.js
styles
index.css (<-- tailwindcss file)
Any hints or advice is very appreciated.
Upvotes: 24
Views: 37013
Reputation: 5035
In .storybook/preview.js
file add this line to compile tailwind generated css files like this -
import '!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css';
Here tailwindcss/tailwind.css
is the tailwind css file. Look, important is I've to add !postcss-loader!
to compile tailwind generated css.
You can add also your custom scss file like this if any -
import '!style-loader!css-loader!sass-loader!../src/scss/style.scss';
Here ../src/scss/style.scss
is custom scss file.
For most of the people this will work in Tailwind version > 3.0 without any issue.
The above solution will not work for Tailwind version > 3.0 because of JIT compiler.
Create a custom styled element in preview page
import tailwindCss from '!style-loader!css-loader!postcss-loader!sass-loader!tailwindcss/tailwind.css';
const storybookStyles = document.createElement('style');
storybookStyles.innerHTML = tailwindCss;
document.body.appendChild(storybookStyles);
Hope, this will help for new Tailwind users who are working in Tailwind greater than v3.0
.
Upvotes: 19
Reputation: 1252
I've reviewed all the posts and discovered that the root issue lies in the Tailwind configuration, specifically in the tailwind.config.ts
file.
Many solutions here are project-specific and don't fully explain the underlying issue. I hope to provide a more generic solution that can be applied universally to various projects.
The issue is that Tailwind doesn't know to JIT compile or hot reload for Storybook files by default. This results in missing styles when using Storybook. When you run Storybook alongside your dev server, it may work because the styles are being compiled and referenced from the dev server, but this is not a reliable setup.
To fix this, you need to tell Tailwind where to find all your project content files using the content
property in your tailwind.config.ts
. This way, Tailwind can properly include your Storybook files in its compilation process.
Here's an example of how to configure this:
const config: Config = {
content: [
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}",
"./src/components/**/*.{js,ts,jsx,tsx,mdx}",
"./src/app/**/*.{js,ts,jsx,tsx,mdx}",
/**
* Add the below line:
* Customise the match pattern to target the Storybook story
* files in your project per your projects directory structure
*/
"./src/stories/**/*.{js,ts,jsx,tsx,mdx}"
],
// ...the rest of the configuration
}
export default config;
In the above configuration:
"./src/pages/**/*.{js,ts,jsx,tsx,mdx}"
specifies to look for all files in the ./src/pages
directory and its subdirectories with extensions js
, ts
, jsx
, tsx
, and mdx
."./src/stories/**/*.{js,ts,jsx,tsx,mdx}"
ensures that Tailwind includes Storybook story files in its compilation process.By including the ./src/stories
directory (you should change this to match where your Storybook files are located), Tailwind can now watch and compile styles for those files correctly.
This approach resolved the issue for me and aims to provide context so that that the solutions should be easily adaptable to other projects.
Upvotes: -1
Reputation: 71
in taiwind config content: ["./src/**/*.{js,jsx,ts,tsx}","./nodemodules/ @yourstorybooklib/**/*.{js,jsx,ts,tsx}"]
Upvotes: -1
Reputation: 1
For tailwind version > 3.0.0 add this import this line in file --> .storybook/preview.ts | js
import '!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css';
Now your tailwind CSS classes will work with storybook build.
Upvotes: 0
Reputation: 51
For anyone using Next.js: Try these
NOTE : In step 2 of the tailwindcss storybook recipe, where you need to Provide Tailwind to stories, the guide suggests importing tailwind.css
file in .storybook/preview.js
as mentioned here.
But for my setup, there was no separate tailwind.css
file, what worked for me instead was that I imported globals.css
file from default Next.js file structure setup as:
In .storybook/preview.ts
:
import '../styles/globals.css';
Provided that tailwind directives are added to globals.css
: This is how my globals.css starts like -
@tailwind base;
@tailwind components;
@tailwind utilities;
...
So, in conclusion, I believe any css file containing base directive imports of tailwindmight just work (I might be wrong) when imported in preview.ts... what I showed above might just work for most Next.js users.
Please leave a comment if it doesn't work.
Upvotes: 3
Reputation: 2510
The solutions mentioned above worked but only partially. I was facing 2 issues:
Solution: Add the path to the stories folder in the tailwind.config.js file.
module.exports = {
content: [
"./pages/**/*.{js,ts,jsx,tsx}",
"./components/**/*.{js,ts,jsx,tsx}",
"./stories/**/*.{js,ts,jsx,tsx}", //needed to make hot reload work with stories
],
theme: {},
plugins: [],
}
Upvotes: 3
Reputation: 19
When you try to create a storybook while using Tailwind CSS, you will notice that the CSS is not being applied. There is a simple solution that has helped me.
Your preview.js
should be like.
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
And you will need to add the following line in the preview.js
to fix it.
// Add the below import line
import "!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css";
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
However this will be a temporary fix. To get this resolved completely, you will need to add the below mentioned package.
yarn add -D @storybook/addon-postcss
For reference, click here How to add postcss
Upvotes: 1
Reputation: 55
For those who are still having this problem and is using postcss >= 8, I suggest you to do as following. Add this to tailwind.config.js
// eslint-disable-next-line @typescript-eslint/no-var-requires
const path = require("path")
module.exports = {
content: [path.join(__dirname, "./src/**/*.(js|jsx|ts|tsx)")],
theme: {
extend: {},
},
variants: {}
plugins: [],
}
Add this to preview.js
import "!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css"
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
}
This has helped me fix the problem and I hope it can help you too
Upvotes: 2
Reputation: 203
I had a similar problem. My problem was solved by adding:
import "../src/index.css";
to .storybook/preview.js
Upvotes: 17
Reputation: 4615
The following configuration will enable so Tailwind generate CSS as new tailwind classes are added to the markup in dev mode (hot reload).
In summary, I don't think @storybook/addon-postcss works with Tailwind JIT and Storybook hot reload, and the workaround is to use the postcss-loader
webpack loader.
Install these deps:
@storybook/builder-webpack5
@storybook/manager-webpack5
postcss-loader
webpack
(must be version 5)
// .storybook/main.js
const path = require("path");
module.exports = {
stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
addons: [
"@storybook/addon-links",
"@storybook/addon-essentials",
"@storybook/addon-interactions",
// {
// name: "@storybook/addon-postcss",
// options: {
// postcssLoaderOptions: {
// implementation: require("postcss"),
// },
// },
// },
],
framework: "@storybook/react",
core: {
builder: "webpack5",
},
webpackFinal: (config) => {
config.module.rules.push({
test: /\.css$/,
use: [
{
loader: "postcss-loader",
options: {
postcssOptions: {
plugins: [require("tailwindcss"), require("autoprefixer")],
},
},
},
],
include: path.resolve(__dirname, "../"),
});
return config;
},
};
// .storybook/preview.js
import "../styles/globals.css";
export const parameters = {
actions: { argTypesRegex: "^on[A-Z].*" },
controls: {
matchers: {
color: /(background|color)$/i,
date: /Date$/,
},
},
};
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
Upvotes: 4
Reputation: 213
if you using storybook with TSdx and tailwind css you should be able to import a CSS into components
Alright, so now let's add rollup-plugin-postcss:
yarn add -D rollup-plugin-postcss
TSDX is fully customizable and you can add any rollup plugin, but be aware that it overrides the default behavior
Now you'll create a
tsdx.config.js
// tsdx.config.js
const postcss = require('rollup-plugin-postcss');
module.exports = {
rollup(config, options) {
config.plugins.push(
postcss({
config: {
path: './postcss.config.js',
},
extensions: ['.css'],
minimize: true,
inject: {
insertAt: 'top',
},
})
);
return config;
},
};
This is giving a postCSS path, which tells it what files you want it to run on. The minimize key is to allow you to minimize the output. The most important key here is the "inject". you set it to "top" to tell postCSS where inside the of our page the CSS will be inserted. It's paramount for Tailwind as it needs to have the utmost priority of any other stylesheet.
Next, for part 2, you will create a tailwind.css (can be named anything else) file under the src directory and paste this in:
// src/tailwind.css
@tailwind base;
@tailwind components;
@tailwind utilities;
Add the CSS import statement to your component
// src/Thing.tsx
import React, { FC, HTMLAttributes, ReactChild } from 'react';
// ! Add the CSS import statement !
import './tailwind.css`;
// ...
// we'll add some Tailwind classes on our components to test
export const Thing: FC<Props> = ({ children }) => {
return (
<div className="flex items-center justify-center w-5/6 m-auto text-2xl text-center text-pink-700 uppercase bg-blue-300 shadow-xl rounded-3xl">
{children || `the snozzberries taste like snozzberries`}
</div>
);
};
Upvotes: 1
Reputation: 533
I couldn't work this out and the above answered didn't work for me, so I eventually just set my build-storybook script to run tailwind itself after the build. package.json scripts looked like this in the end:
"build-storybook": "build-storybook -s public && $(npm bin -g)/tailwindcss -i storybook-static/static/css/main.*.chunk.css -o storybook-static/static/css/main.*.chunk.css -m",
Bit of a mess, but $(npm bin -g)/
here uses my globally installed (npm i -g tailwindcss
) version of tailwindcss as the version installed to the project wasn't working in builds for me.
-i and -o specifies the input and output files, and -m minifies the output.
I can foresee this causing problems if more than one CSS file gets built (maybe using storybook-static/static/css/**/*.css
would work instead?), but this might help someone just get something working.
Upvotes: 0
Reputation: 632
UPDATE: My original answer could be useful to others, so I'll leave it for reference. However, in this case, the problem was in tailwind.config.js.
Change
purge: {
mode: 'all',
content: [
'./src/components/**/**/*.{ts, tsx}'
],
},
to
purge: ['./src/**/*.{js,jsx,ts,tsx}'],
ORIGINAL:
Just tested it out and storybook builds as expected for me. I think the key difference in our configurations is that I am not making changes to Storybook's webpack config in main.js. Rather, I am using @storybook/addon-postcss for postcss@^8 (required for tailwind@^2):
// main.js
module.exports = {
...
addons: [
...
{
name: '@storybook/addon-postcss',
options: {
postcssLoaderOptions: {
implementation: require('postcss'),
},
},
},
],
};
I specify the necessary plugins in a postcss.config.js (in my project root):
// postcss.config.js
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
It's also worth noting that I import Tailwind directly in Storybook's preview.js instead via my own css file:
// preview.js
import 'tailwindcss/tailwind.css';
export const parameters = {...}
Hopefully, making those changes will get Tailwind working for you.
For comparison (see comments below), here are the contents of my build storybook-static directory:
Upvotes: 18