tailwindlabs / tailwindcss

A utility-first CSS framework for rapid UI development.
https://tailwindcss.com/
MIT License
83.1k stars 4.21k forks source link

tailwind 3 doesn't work with storybook/webpack setup #6314

Closed sachinmour closed 2 years ago

sachinmour commented 2 years ago

I'm using macOS, Chrome v96, Node.js 16

I created a github repository with this exact issue - https://github.com/sachinmour/tailwind-issue

Basically just do yarn and yarn storybook and you'll see storybook loaded correctly. change package.json to use tailwind ^3.0.0 and run yarn and yarn storybook again and you'll see no tailwind is loaded inside storybook.

paulgendek commented 2 years ago

I'm having a similar issue. I tried forcing Storybook to use PostCSS 8+ per the docs, but get the following error:

ModuleBuildError: Module build failed (from ./node_modules/postcss-loader/dist/cjs.js):
SyntaxError

(2:7) .storybook/tailwind-imports.css Unknown word

  1 | 
> 2 |       import API from "!../../../../../../node_modules/@nrwl/web/node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js";
    |       ^
  3 |       import domAPI from "!../../../../../../node_modules/@nrwl/web/node_modules/style-loader/dist/runtime/styleDomAPI.js";
  4 |       import insertFn from "!../../../../../../node_modules/@nrwl/web/node_modules/style-loader/dist/runtime/insertBySelector.js";
sachinmour commented 2 years ago

I'm having a similar issue. I tried forcing Storybook to use PostCSS 8+ per the docs, but get the following error:

ModuleBuildError: Module build failed (from ./node_modules/postcss-loader/dist/cjs.js):
SyntaxError

(2:7) .storybook/tailwind-imports.css Unknown word

  1 | 
> 2 |       import API from "!../../../../../../node_modules/@nrwl/web/node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js";
    |       ^
  3 |       import domAPI from "!../../../../../../node_modules/@nrwl/web/node_modules/style-loader/dist/runtime/styleDomAPI.js";
  4 |       import insertFn from "!../../../../../../node_modules/@nrwl/web/node_modules/style-loader/dist/runtime/insertBySelector.js";

@paulgendek your error is probably due to webpack 5, because style-loader doesn't support webpack version below 5. https://github.com/webpack-contrib/style-loader/releases/tag/v3.0.0

LinnJS commented 2 years ago

I have been working on a TailwindCSS component library for some time now. It took me forever to get Tailwind v2 working with Storybook nicely. I just upgraded to Tailwind V3 and had no issues like this.

My main.js file looks like this:

module.exports = {
  stories: ["../src/**/*.stories.mdx", "../src/**/*.stories.@(js|jsx|ts|tsx)"],
  addons: [
    "@storybook/addon-links",
    "@storybook/addon-essentials",
    "storybook-addon-designs",
    {
      name: "@storybook/addon-postcss",
      options: {
        postcssLoaderOptions: {
          implementation: require("postcss"),
        },
      },
    },
  ],
};

and my preview.js file looks like:

import 'normalize.css';
import '../src/tailwind.css';

Not sure if this helps but I cant seem to reproduce your all's error. I do have a similar error with my GatsbyJS project though 🙁 which is how I found this issue.

paulgendek commented 2 years ago

We were able to get this working by NOT using @storybook/addon-postcss and moving a copy of postcss.config.js and tailwind.config.js into the .storybook directory.

.storybook/postcss.config.js:

const { join } = require('path');

module.exports = {
  plugins: {
    tailwindcss: {
      config: join(__dirname, 'tailwind.config.js')
    },
    autoprefixer: {}
  }
};

./storybook/tailwind.config.js:

const { join } = require('path');

module.exports = {
  presets: [require('../tailwind.config.js')],
  content: [join(__dirname, '../libs/**/*.(js|jsx|ts|tsx)')],
  theme: {},
  plugins: []
};

Everything else is the traditional setup (following the v3 upgrade guide).

sachinmour commented 2 years ago

@LinnJS @paulgendek if you can post a working repo or link, that'd be great.

nvsd commented 2 years ago

@LinnJS @paulgendek if you can post a working repo or link, that'd be great.

https://github.com/nvsd/storybook-tailwind-3

This is hacky but this is what I'm doing based on the answers above.

better solution

sachinmour commented 2 years ago

@nvsd @LinnJS @paulgendek so, I figured out what the problem was, I don't think it was because of what you guys said. The problem is in v3 of tailwindcss has JIT enabled by default and that means it'll only add css that you use in your components, and in v2 if you didn't define mode and left the purge config as an empty array, it would add all of tailwindcss, but now you MUST define content property with all the places you're using tailwindcss and as soon as I updated content to include my src folder, everything started working as usual. I've updated my original repo with working code https://github.com/sachinmour/tailwind-issue

If you guys don't agree, let me know, otherwise, I'll close this issue in 2 days.

nvsd commented 2 years ago

@sachinmour Ah yea, that makes sense. Using your repo as a guide got me up and running without multiple configs.

junaidrasheed commented 2 years ago

Hi, we recently upgraded from v2 to v3 and after the upgrade, webpack has to be restarted every time in order for the JIT engine to compile new classes. Any help would be appreciated.

Here is the webpack config

#!/usr/bin/env ruby

ENV["RAILS_ENV"] ||= ENV["RACK_ENV"] || "development"
ENV["NODE_ENV"]  ||= "development"

require "pathname"
ENV["BUNDLE_GEMFILE"] ||= File.expand_path("../../Gemfile",
  Pathname.new(__FILE__).realpath)

require "bundler/setup"

require "webpacker"
require "webpacker/dev_server_runner"

APP_ROOT = File.expand_path("..", __dir__)
Dir.chdir(APP_ROOT) do
  Webpacker::DevServerRunner.run(ARGV)
end

And postcss config

module.exports = {
  plugins: [
    require('tailwindcss')('tailwind.config.js'),
    require('autoprefixer'),
    require('postcss-import'),
    require('postcss-flexbugs-fixes'),
    require('postcss-preset-env')({
      autoprefixer: {
        flexbox: 'no-2009'
      },
      stage: 3
    })
  ]
};

and tailwind config

const plugin = require('tailwindcss/plugin');
const colors = require('tailwindcss/colors');

module.exports = {
  content: ['./app/views/**/*.html.erb', './app/javascript/**/*.vue', './app/javascript/**/*.js'],
  theme: {
    colors: {
      // ...colors,
      transparent: 'transparent',
      current: 'currentColor',
      // used mostly for borders and light text
      secondary: colors.slate['400'],
      grid: colors.slate['700']
    },
    extend: {
      spacing: {
        98: '31.5rem',
        104: '36rem',
        110: '42rem'
      },
      fontFamily: {
        sans: ['Inter', 'sans-serif']
      },
    },
    customForms: theme => ({
      default: {
        checkbox: {
          backgroundColor: theme('colors.gray.600'),
          '&:focus': {
            outline: 'none',
            boxShadow: 'none',
            borderColor: 'none'
          }
        }
      }
    })
  },
  variants: {
    textColor: ({ after }) => after(['invalid']),
    extend: {
      zIndex: ['hover', 'active']
    }
  },
  plugins: [
    require('@tailwindcss/line-clamp'),
    require('@tailwindcss/forms')({
      strategy: 'class'
    }),
    plugin(function ({ addVariant, e }) {
      addVariant('invalid', ({ modifySelectors, separator }) => {
        modifySelectors(({ className }) => {
          return `.${e(`invalid${separator}${className}`)}:invalid`;
        });
      });
    })
  ]
};
nvsd commented 2 years ago

@junaidrasheed You'll likely get much quicker help posting this in discussions since this doesn't relate to the issue.

reinink commented 2 years ago

@nvsd @LinnJS @paulgendek so, I figured out what the problem was, I don't think it was because of what you guys said. The problem is in v3 of tailwindcss has JIT enabled by default and that means it'll only add css that you use in your components, and in v2 if you didn't define mode and left the purge config as an empty array, it would add all of tailwindcss, but now you MUST define content property with all the places you're using tailwindcss and as soon as I updated content to include my src folder, everything started working as usual. I've updated my original repo with working code https://github.com/sachinmour/tailwind-issue

Hey! Glad you got it figured out. Be sure to review the upgrade guide, which goes over all these requirements in detail.

Also, just a heads up that Tailwind CSS v3.0 requires PostCSS 8, and no longer supports PostCSS 7. If you can’t upgrade to PostCSS 8, we recommend using Tailwind CLI instead of installing Tailwind as a PostCSS plugin.

Hope that helps! 💪

ManiruzzamanAkash commented 2 years ago

Hi, the above staffs didn't worked for me. here is the quick solution - 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.

There are more solutions answered here - https://stackoverflow.com/a/70805809/5543577

paulwongx commented 2 years ago

@ManiruzzamanAkash answer almost fully worked for me. I also needed to add the line below for it to hot reload.

import 'tailwindcss/tailwind.css';

I documented the full setup below in case anyone else is struggling as this took me a day - includes setting up absolute paths. Question is how to setup Storybook with TailwindcssV3, ReactJS and Typescript: https://stackoverflow.com/questions/71329335/how-to-setup-storybook-with-tailwindcss-reactjs-and-typescript

jrock2004 commented 2 years ago

What is the solution here as I have tried some of these things and it just does not work. Which solution is the reason we closed this?

callumzhong commented 2 years ago

@jrock2004 What is the solution here as I have tried some of these things and it just does not work. Which solution is the reason we closed this?

I have the same problem, but the following solutions helped me. https://stackoverflow.com/a/71877841/18970146

L0rdCr1s commented 2 years ago

If anyone is still having issues with this, here is what I did step by step

Install storybook postcss addon

yarn add -D @storybook/addon-postcss

Add it into your .storybook/main.js file

module.exports = {
  addons: [
    {
      name: '@storybook/addon-postcss',
      options: {
        postcssLoaderOptions: {
          implementation: require('postcss'),
        },
      },
    },
  ],
}

import tailwind into your .storybook/preview.js file

import 'tailwindcss/tailwind.css';

restart storybook server and hopefully tailwind will work with storybook

yarn storybook
Amethystafyy282 commented 2 years ago

If anyone is still having issues with this, here is what I did step by step

Install storybook postcss addon

yarn add -D @storybook/addon-postcss

Add it into your .storybook/main.js file

module.exports = {
  addons: [
    {
      name: '@storybook/addon-postcss',
      options: {
        postcssLoaderOptions: {
          implementation: require('postcss'),
        },
      },
    },
  ],
}

import tailwind into your .storybook/preview.js file

import 'tailwindcss/tailwind.css';

restart storybook server and hopefully tailwind will work with storybook

yarn storybook

Thank you so much, but only tailwind classes in build time work, classes in hot reload didnt work at all. Did u manage to accomplish this? Thank you.

jrock2004 commented 2 years ago

@jrock2004 What is the solution here as I have tried some of these things and it just does not work. Which solution is the reason we closed this?

I have the same problem, but the following solutions helped me. https://stackoverflow.com/a/71877841/18970146

I am still trying to figure this out. Seems like tailwind and storybook just are not friends right now

alirezamajdi commented 2 years ago
import '!style-loader!css-loader!postcss-loader!tailwindcss/tailwind.css';

Hi, the above staffs didn't worked for me. here is the quick solution - 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.

There are more solutions answered here - https://stackoverflow.com/a/70805809/5543577

Tanks a lot.

vatana7 commented 2 years ago

@jrock2004 For those who are still having this problem and is using postcss >= 8, I suggest you to do as following. Note: Credit to OP of these fixes. Thanks to them my project is working fine now.

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

jrock2004 commented 2 years ago

I can confirm from @vatana7 that this did work for me just fine

NatoBoram commented 1 year ago

From https://github.com/tailwindlabs/tailwindcss/issues/6314#issuecomment-991077481, what I was missing was import '../src/app.css' inside .storybook/preview.cjs.

danialdezfouli commented 1 year ago

setup: React + Vite + storybook + tailwind I'm loading the tailwind file in the preview.tsx

I have an issue with the priority of loading the tailwind.css file and my component CSS file in the storybook.

<button class="btn h-10"></button> this is ok in the app, and the CSS will be like this:

.btn { ... }
.h-10{ ... }

But in the storybook, it causes to ignore tailwind CSS styles:

.h-10{ ... }
.btn { ... }

Hence I have to use @layer components for every overlap to fix this in the storybook the problem here is there will be a lot of non-related classes inside this tailwind.css file, and will not allow me to use react modular CSS files (style.module.css)

@layer components {
  .btn {
  }
}
gtrak commented 1 year ago

~With the import '!style-loader!css-loader!postcss-loader!{the-file} hack I was able to remove the storybook postcss addon, and hot reloads also work. Thanks.~

EDIT: I needed neither the loader prefixes nor the addon for some reason.

hossam1231 commented 1 year ago

if anyone needs help just let me know ive done this easily in the islamic-ware repo