storybookjs / addon-postcss

This Storybook addon can be used to run the PostCSS preprocessor against your stories.
MIT License
20 stars 22 forks source link

[Bug] unknown word error with CRA + tailwindcss #33

Closed sshquack closed 2 years ago

sshquack commented 2 years ago

Describe the bug

CRA now comes with Webpack 5 by default. Created a vanilla CRA typescript template with TailwindCSS. It throws the following error:

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

(1:1) /Users/user/Desktop/code/js/react-ts-tw-sb-01/src/index.css Unknown word

> 1 | var api = require("!../node_modules/@storybook/addon-postcss/node_modules/style-loader/dist/runtime/injectStylesIntoStyleTag.js");
    | ^
  2 |             var content = require("!!../node_modules/@storybook/addon-postcss/node_modules/css-loader/dist/cjs.js!../node_modules/@storybook/addon-postcss/node_modules/postcss-loader/dist/cjs.js??ruleSet[1].rules[6].use[2]!./index.css");
  3 | 

    at processResult (/Users/user/Desktop/code/js/react-ts-tw-sb-01/node_modules/webpack/lib/NormalModule.js:751:19)
    at /Users/user/Desktop/code/js/react-ts-tw-sb-01/node_modules/webpack/lib/NormalModule.js:853:5
    at /Users/user/Desktop/code/js/react-ts-tw-sb-01/node_modules/loader-runner/lib/LoaderRunner.js:399:11
    at /Users/user/Desktop/code/js/react-ts-tw-sb-01/node_modules/loader-runner/lib/LoaderRunner.js:251:18
    at context.callback (/Users/user/Desktop/code/js/react-ts-tw-sb-01/node_modules/loader-runner/lib/LoaderRunner.js:124:13)
    at Object.loader (/Users/user/Desktop/code/js/react-ts-tw-sb-01/node_modules/postcss-loader/dist/index.js:140:7)

Steps to reproduce the behavior

Expected behavior

To not throw error

Screenshots and/or logs

Full issue repro at https://github.com/sshquack/react-ts-tw-sb-01

Environment

    System:
      OS: macOS 12.1
      Shell: 5.8 - /bin/zsh
    Binaries:
      Node: 16.13.1 - ~/.nvm/versions/node/v16.13.1/bin/node
      npm: 8.3.0 - ~/.nvm/versions/node/v16.13.1/bin/npm
    npmPackages:
      react: ^17.0.2 => 17.0.2
      react-dom: ^17.0.2 => 17.0.2
      storybook: 6.4.9
      addon-postcss: 2.0.0

Additional context

Full issue repro at https://github.com/sshquack/react-ts-tw-sb-01

cdesch commented 2 years ago

@sshquack any luck with this issue?

sshquack commented 2 years ago

No luck. I got rid of storybook and created a simple /components route to view my components.

Note that this plugin has pretty been abandoned and the storybook team has other priorities. So the chances of all the issues in this repo getting fixed is pretty low. So use best judgment.

cdesch commented 2 years ago

Thanks. That helps!

sshquack commented 2 years ago

FWIW I've moved all my components to use Ladle (by Uber team).

carloschneider commented 2 years ago

Solution: https://github.com/tailwindlabs/tailwindcss/issues/6314#issuecomment-991824049

FYI: @sshquack

carloschneider commented 2 years ago

Basically in tailwind.config.js you must specify the content option like this:

const path = require('path')

module.exports = {
  content: [path.join(__dirname, './src/**/*.{js,jsx,ts,tsx}')],
  theme: {
    extend: {},
  },
  plugins: [],
}
alissaVrk commented 2 years ago

I still get the same error, though I changed the content

carloschneider commented 2 years ago

@alissaVrk I created a new project to test, and in fact, the change in content is not necessary. I only added the CSS file in .storybook/preview.js

You can see here: https://github.com/carloschneider/storybook-tailwind

malikalimoekhamedov commented 2 years ago

After many days of trial and error, I managed to get this to work.

The most important thing to understand is that the building process of a CRA application with TailwindCSS set up according to the documentation differs from the building process of Storybook. Therefore, one should bend over backwards to bypass the building process of the main project and accommodate for what Storybook expects. Here comes my configuration that uses the latest and greatest from React, Webpack, PostCSS, Tailwind and Storybook in terms of NPM packets versions.

// postcss.config.js

module.exports = {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
};
// tailwind.config.js

module.exports = {
  // mode: 'jit', <--- Don't activate 'JIT' mode. Storybook is not playing well with it.
  content: ['./src/**/*.{js,jsx,ts,tsx}', './public/index.html'], // <--- Make sure you use the latest convention. Not the 'prune' one.
  ...
  plugins: [require('@tailwindcss/forms')], // <---- Don't put Tailwind related plugins elsewhere but in this file. Notice that 'require('tailwindcss'), require('autoprefixer')' are not included in this array.
};
// package.json

{
   "devDependencies": {
      ...
      "autoprefixer": "^10.4.7",
      ...
      "@storybook/addon-postcss": "^2.0.0",
      "@storybook/builder-webpack5": "^6.5.9",
      "@storybook/manager-webpack5": "^6.5.9",
      "@storybook/node-logger": "^6.5.9",
      "@storybook/preset-create-react-app": "4.1.2",
      "@storybook/react": "^6.5.9",
      ...
     "postcss": "^8.4.14", <--- Important if you want to use latest and greatest like I do.
     "postcss-loader": "^7.0.0", <--- Important to have a recent version as the version that comes bundled with other packages will be too old for the modern postcss package.
      ...
      "tailwindcss": "^3.1.4",
      ...
      "webpack": "5.73.0"
   }
}
// .storybook/main.js

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

module.exports = {
  stories: [
    path.resolve(__dirname, '../src/**/*.stories.mdx'),
    path.resolve(__dirname, '../src/**/*.stories.@(js|jsx|ts|tsx)'),
  ],

  /** Expose public folder to storybook as static */
  staticDirs: [path.resolve(__dirname, '../public')],
  addons: [
    '@storybook/addon-links',
    '@storybook/addon-essentials',
    '@storybook/addon-interactions',
    '@storybook/preset-create-react-app',

    //{ <--- Notice how I'm bypassing @storybook/addon-postcss.
    // I'm commenting it out as I'm waiting for this thing to catch up and work properly with normal Tailwind project setup as described in their documentation.

    //  name: '@storybook/addon-postcss',
    //  options: {
    //    cssLoaderOptions: {
    //      // When you have splitted your css over multiple files
    //      // and use @import('./other-styles.css')
    //      importLoaders: 1,
    //    },
    //    postcssLoaderOptions: {
    //      implementation: require('postcss'),
    //    },
    //  },
    //},
  ],
  framework: '@storybook/react',
  core: {
    builder: 'webpack5',
  },

  // <--- This is the important bit. It's where I use a different postprocessing method using the latest version of 'postcss-loader'.

  webpackFinal: async (config) => {
    config.module.rules.push({
      test: /\.css$/,
      use: [
        {
          loader: 'postcss-loader',
          options: {
            postcssOptions: {
              plugins: [require('tailwindcss'), require('autoprefixer')],
            },
          },
        },
      ],
      include: path.resolve(__dirname, '../'),
    });
    config.resolve.plugins = [
      ...(config.resolve.plugins || []),
      new TsconfigPathsPlugin({
        extensions: config.resolve.extensions,
      }),
    ];
    return config;
  },
};
// .storybook/preview.js

// <--- The following two lines are critical too. You should make sure you don't process an already processed CSS once more or else you'll get the 'unknown word var' error.

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

export const parameters = {
  actions: { argTypesRegex: '^on[A-Z].*' },
  controls: {
    matchers: {
      color: /(background|color)$/i,
      date: /Date$/,
    },
  },
};

And that's it, folks!

Normally, such configuration should allow you to use the latest and greatest of NPM packages and make React, TailwindCSS and Storybook coexist in harmony until '@storybook/addon-postcss' catches on. Let me know if this doesn't cut the mustard.

aaldhahe commented 1 year ago

This did not work for me. I no longer see errors but I don't see the styles in my components.

FJKhan commented 1 year ago

if you're using postcss 8+ , add @storybook/addon-styling and then update your storybook config as shown below

// .storybook/main.js

const config = {
  ...
    addons: [
     ...
      {
         name: '@storybook/addon-styling',
         options: {
            implementation: require("postcss"), // <---- this is specifically for postcss 8
         },
      },
   ],
  ...
}
timeturnback commented 9 months ago

Thanks malikalimoekhamedov

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

export const parameters = {
  actions: { argTypesRegex: '^on[A-Z].*' },
  controls: {
    matchers: {
      color: /(background|color)$/i,
      date: /Date$/,
    },
  },
};

This work for me