storybook: [Bug]: Angular - Storybook fails to consume postcss config file

Describe the bug

In order to use Tailwindcss v4 with Angular 19+ (using the new esbuild builder), it is necessary to create a postcss.config.json file, because Angular seemingly fails to consume any other variant of a postcss config (e.g. in the package.json, or using a postcss.config.mjs).

Installing Tailwindcss v4 with postCSS: https://tailwindcss.com/docs/v4-beta#installing-with-post-css Trying to compile the angular app, without this postcss.config.json file present, will result in

Error: It looks like you're trying to use `tailwindcss` directly as a PostCSS plugin. The PostCSS plugin has moved to a separate package, so to continue using Tailwind CSS with PostCSS you'll need to install `@tailwindcss/postcss` and update your PostCSS configuration.

Once the postcss.config.json is provided - and both ng serve, ng test and ng build run smoothly, Storybook fails to compile for the same reason, as the builder (under the hood) seemingly fails to consume said postcss config.

Error: It looks like you're trying to use `tailwindcss` directly as a PostCSS plugin. The PostCSS plugin has moved to a separate package, so to continue using Tailwind CSS with PostCSS you'll need to install `@tailwindcss/postcss` and update your PostCSS configuration.

This is using the Webpack builder. I am aware that there is a plugin that tries to get Angular to run under Storybook using vite.

Reproduction link

https://github.com/SeraphCoding/AngularTW4SBVite

Reproduction steps

  1. Clone the repository above
  2. Install dependencies (yarn berry)
  3. Run yarn run storybook
  4. Wait for the compilation

System

Storybook Environment Info:

  System:
    OS: Linux 5.15 Ubuntu 24.04.1 LTS 24.04.1 LTS (Noble Numbat)
    CPU: (16) x64 AMD Ryzen 7 3800X 8-Core Processor
    Shell: 5.2.21 - /bin/bash
  Binaries:
    Node: 20.15.0 - /tmp/xfs-ade9681f/node
    Yarn: 4.6.0 - /tmp/xfs-ade9681f/yarn <----- active
    npm: 10.7.0 - ~/.nvm/versions/node/v20.15.0/bin/npm
  npmPackages:
    @storybook/addon-docs: ^8.4.7 => 8.4.7
    @storybook/addon-essentials: ^8.4.7 => 8.4.7
    @storybook/addon-interactions: ^8.4.7 => 8.4.7
    @storybook/addon-onboarding: ^8.4.7 => 8.4.7
    @storybook/angular: ^8.4.7 => 8.4.7
    @storybook/blocks: ^8.4.7 => 8.4.7
    @storybook/test: ^8.4.7 => 8.4.7
    storybook: ^8.4.7 => 8.4.7


**Note**
Same issues occurs on 8.5.0-beta.7

Additional context / WIP Workaround

The issue does not occur when using analogjs’s angular vite plugin for the Storybook - however, I haven’t been able to get the analogjs plugin to run properly in it’s completion. I managed to get it to compile, though it seemingly fails to load Tailwindcss and Angular Material to begin with - so that isn’t really a sustainable workaround, yet. Will update this once/if I get it to run.

Workaround using vite: https://github.com/storybookjs/storybook/issues/30208#issuecomment-2830668556 Workaround using postcss-loader in the webpack config: https://github.com/storybookjs/storybook/issues/30208#issuecomment-2688459931

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 9
  • Comments: 29 (1 by maintainers)

Most upvoted comments

Thanks @benjamin-gooding for the investigation. I fixed this problem in my project by adding this to the StorybookConfig object in .storybook/main.ts :

const config: StorybookConfig = {
        ...
        webpackFinal: async (config) => {
            config.module?.rules?.push({
              test: /\.css$/,
              use: [
                {
                  loader: "postcss-loader",
                  options: {
                    postcssOptions: {
                      plugins: [
                        require('@tailwindcss/postcss')
                      ]
                    }
                  }
                },
              ],
              include: path.resolve(__dirname, '../'),
            })
            return config
          }

Unless I am missing something it seems that @storybook/angular will not work at all with Tailwind 4?

I investigated a little this morning and it looks like the Tailwind < v4 and @storybook/angular relies on the following code in node_modules/@angular-devkit/build-angular/src/tools/webpack/configs/styles.js which throws the exception

“Error: It looks like you’re trying to use tailwindcss directly as a PostCSS plugin. The PostCSS plugin has moved to a separate package, so to continue using Tailwind CSS with PostCSS you’ll need to install @tailwindcss/postcss and update your PostCSS configuration.”

when a tailwind.config.js is present.

    const extraPostcssPlugins = [];
    // Attempt to setup Tailwind CSS
    // Only load Tailwind CSS plugin if configuration file was found.
    // This acts as a guard to ensure the project actually wants to use Tailwind CSS.
    // The package may be unknowningly present due to a third-party transitive package dependency.
    const tailwindConfigPath = await (0, tailwind_1.findTailwindConfigurationFile)(root, projectRoot);
    if (tailwindConfigPath) {
        let tailwindPackagePath;
        try {
            tailwindPackagePath = require.resolve('tailwindcss', { paths: [root] });
        }
        catch {
            const relativeTailwindConfigPath = path.relative(root, tailwindConfigPath);
            logger.warn(`Tailwind CSS configuration file found (${relativeTailwindConfigPath})` +
                ` but the 'tailwindcss' package is not installed.` +
                ` To enable Tailwind CSS, please install the 'tailwindcss' package.`);
        }
        if (tailwindPackagePath) {
            extraPostcssPlugins.push(require(tailwindPackagePath)({ config: tailwindConfigPath }));
        }
    }

The current @storybook/angular implementation seems to circumvent the Angular devkit postcss-configuration code which is why the .postcssrc.json is ignored.

This got Tailwind v4 working, though only a spike and not a long term solution.

    // const tailwindConfigPath = true;
    // if (tailwindConfigPath) {
    //     let tailwindPackagePath;
    //     try {
            let tailwindPackagePath = require.resolve('@tailwindcss/postcss', { paths: [root] });
        // }
        // catch {
        //     const relativeTailwindConfigPath = path.relative(root, tailwindConfigPath);
        //     logger.warn(`Tailwind CSS configuration file found (${relativeTailwindConfigPath})` +
        //         ` but the 'tailwindcss' package is not installed.` +
        //         ` To enable Tailwind CSS, please install the 'tailwindcss' package.`);
        // }
        // if (tailwindPackagePath) {
            extraPostcssPlugins.push(require(tailwindPackagePath)());
        // }
    // }

I’m working on this - Team (Amormio, Neenu, William)

Did anyone has reached to a solution?

This is an alternative to this solution https://github.com/storybookjs/storybook/issues/30208#issuecomment-2688459931 . The linked solution uses webpack and postcss-loader. This one uses vite as a builder.

I’ve got it running with the setup below. This is a yucky workaround, hope Storybook just implements it themselves. Maybe someone can take this solution and reduce it to what is actually minimally needed to make it run.

You’ll need 2 postcss config files.

Uses tw4 and the entire theme config is in the styles.scss. Make sure your application builder uses.

"styles": ["src/styles.scss"], // or equivalent
"@analogjs/vite-plugin-angular": "^1.15.1"
"storybook": "^8.6.12",
"postcss": "^8.5.3",
"tailwindcss": "4.1.4",
"vite-tsconfig-paths": "^5.1.4"
"typescript": "~5.8.3",
"@angular/material": "19.2.11",
"vite-tsconfig-paths": "^5.1.4"

And Angular on 19.8.2 Node Version 22.10.0

Essentially using vite as a builder for the storybook.

preview.ts

import 'zone.js'; // <-- Important! needed for the angular vite plugin
import type { Preview } from '@storybook/angular';
import '../src/styles.scss';
import { applicationConfig } from '@storybook/angular/dist/client/decorators';
import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http';

const preview: Preview = {
  decorators: [
    applicationConfig({
      providers: [
        provideAnimations(),
        provideHttpClient(),
       //... Whatever you may need
      ],
    }),
  ],
  parameters: {
    controls: {
      matchers: {
        color: /(background|color)$/i,
        date: /Date$/i,
      },
    },
  },
};

export default preview;

main.ts

import type { StorybookConfig } from '@storybook/angular';
import { StorybookConfigVite } from '@storybook/builder-vite';
import { UserConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';

const config: StorybookConfig & StorybookConfigVite = {
  stories: ['../src/**/*.mdx', '../src/**/*.stories.@(js|jsx|mjs|ts|tsx)'],
  addons: [
    '@storybook/addon-onboarding',
    '@storybook/addon-essentials',
    '@storybook/addon-interactions',
    '@storybook/addon-a11y',
  ],
  framework: {
    name: '@storybook/angular',
    options: {},
  },
  core: {
    disableTelemetry: true,
    enableCrashReports: false,
    builder: {
      name: '@storybook/builder-vite',
      options: {
        viteConfigPath: undefined,
      },
    },
  },
  async viteFinal(config: UserConfig) {
    // Resolve the path aliases
    // Merge custom configuration into the default config
    const { mergeConfig } = await import('vite');
    const { default: angular } = await import('@analogjs/vite-plugin-angular');
    return mergeConfig(config, {
      // Add dependencies to pre-optimization
      optimizeDeps: {
        include: [
          '@storybook/angular',
          '@storybook/angular/dist/client',
          '@storybook/angular/dist/client/decorators.js',
          '@storybook/angular/dist/client/docs/config.js',
          '@storybook/angular/dist/client/config.js',
          '@storybook/addon-interactions/preview',
          '@storybook/addon-docs/angular',
          '@angular/compiler',
          '@storybook/test',
          '@storybook/blocks',
          'tslib',
        ],
        exclude: ['node_modules/.cache/sb-vite'],
      },
      define: { // <--- VERY IMPORTANT
        STORYBOOK_ANGULAR_OPTIONS: {
          experimentalZoneless: false,
        },
      },
      plugins: [
        angular({ jit: true, tsconfig: './.storybook/tsconfig.json' }),
        tsconfigPaths(),
      ],
    });
  },
};
export default config;

No clue if the pre-optimizations do anything useful building takes forever regardless. Someone with more vite knowledge may enlighten me, thanks.

In your stories, make sure you import functions etc. directly from their files, for some reason the vite builder needs this. e.g.

import { moduleMetadata } from '@storybook/angular/dist/client/decorators';
import { argsToTemplate } from '@storybook/angular/dist/client/argsToTemplate';

In your project, have both a postcss.config.json and postcss.config.mjs on the root of the project. For the JSON

{
  "plugins": [["@tailwindcss/postcss", {}]]
}

For the mjs

export default {
  plugins: {
    "@tailwindcss/postcss": {},
  },
};

The guide on how to setup the angular vite storybook plugin contains instructions to update the angular.json and replace the builder. (see: https://analogjs.org/docs/integrations/storybook ) however there is absolutely no need to do that, whatsoever.

In fact I’ve removed the storybook targets/builders entirely from the angular.json

Make sure you run the storybook dev server fresh - dont trust the vite auto recompile when doing deeper level work, do a full re-compile.

This should just work.

Edit: Some troubleshooting you might run into on different SB versions. Had it running with a similar setup on diff versions as well. Small changes like not needing the STORYBOOK_ANGULAR_OPTIONS in Storybook 8.5.x or the zone.js import in the preview.ts (also 8.5.x) might be things you may run into.

Also if you’re on an older SB version, the whole shenanigans with vite needing the exact file for imports in the stories might look different for you - as they’ve moved or sometimes aren’t required, etc.etc.

@sukrutsathaye adding the postcss-loader to the webpack config worked for me. However I had to rename the tailwind.config.ts to something like storybook-tailwind.config.ts since the Angular CLI (node_modules/@angular-devkit/build-angular/src/tools/webpack/configs/styles.js) detects common tailwind config names and adds the v3 postcss config. Which leads to the error: It looks like you're trying to use tailwindcss directly as a PostCSS plugin.

This was the information lacking. As soon as I renamed my tailwind config file, things just worked. I didn’t even need to mess with the StorybookConfig object.

I take it back, because I’ve deleted and recreated my angular project over and over and over again and can’t get any of the styles to come across to Storybook.

Okay the error seems to come from my tailwind config (weird it has always run smoothly before) I’ll dig into this

@sukrutsathaye adding the postcss-loader to the webpack config worked for me. However I had to rename the tailwind.config.ts to something like storybook-tailwind.config.ts since the Angular CLI (node_modules/@angular-devkit/build-angular/src/tools/webpack/configs/styles.js) detects common tailwind config names and adds the v3 postcss config. Which leads to the error: It looks like you're trying to use tailwindcss directly as a PostCSS plugin.

Just leaving that here in case anyone else runs into the same problem.

index.css

@import "tailwindcss";
@config "../storybook-tailwind.config.ts";

.storybook/main.ts

const config: StorybookConfig = {
  stories: ['./**/*.@(mdx|stories.@(js|jsx|ts|tsx))'],
  addons: [
    '@storybook/addon-docs',
    '@storybook/addon-essentials',
    '@storybook/addon-controls',
    '@storybook/addon-viewport',
  ],
  webpackFinal: (config) => {
    config.module?.rules?.push({
      test: /\.css$/,
      exclude: /node_modules/,
      use: [
        {
          loader: 'postcss-loader',
          options: {
            postcssOptions: {
              plugins: ['@tailwindcss/postcss'],
            },
          },
        },
      ],
    });
    return config;
  },
  framework: {
    name: '@storybook/angular',
    options: {},
  },
};

export default config;

storybook-tailwind.config.ts

import { createGlobPatternsForDependencies } from '@nx/angular/tailwind';
import { tailwindPresetConfig } from '../../libs/tw/src/tailwind/tailwind-preset.config';

const content = createGlobPatternsForDependencies(__dirname, '**/*.{ts,html}');
/** @type {import('tailwindcss').Config} */
export default {
  content,
  presets: [{ ...tailwindPresetConfig, content }],
  theme: {
    extend: {},
  },
  plugins: [],
};

@mathieu-massaviol I hope this step will be integrated to solve this in the future, as I didn’t have this issue in the previous version of Tailwind. So far, I also used the same webpackFinal configuration to integrate Tailwind v4.

The current Storybook documentation offers this recipe to integrate Tailwind, and it unfortunately doesn’t work with Vite + Angular. Link

// ./storybook/main.ts
import type { StorybookConfig } from '@storybook/angular'

export default {
    addons: [
        '@storybook/addon-links',
        '@storybook/addon-essentials',
        '@storybook/addon-interactions',
    ],
    env: (config) => ({
        ...config,
        NODE_ENV: 'development',
    }),
    framework: {
        name: '@storybook/angular',
        options: {},
    },
    staticDirs: [{ from: '../public', to: '/' }],
    stories: ['../src/**/*.mdx', '../src/**/*.stories.ts'],
    webpackFinal: async (config) => {
        config.module?.rules?.push({
            test: /\.css$/,
            exclude: /node_modules/,
            use: [
                {
                    loader: 'postcss-loader',
                    options: {
                        postcssOptions: {
                            plugins: ['@tailwindcss/postcss'],
                        },
                    },
                },
            ],
        })
        return config
    },
} satisfies StorybookConfig

[!IMPORTANT]
We are using it for development proposes. For now, we will review the building process and deployment.

I’ve tried the above comment https://github.com/storybookjs/storybook/issues/30208#issuecomment-2636372822 but I had inconsistent results with getting a black and white HTML page and a dysfunctional Storybook display which would have the loading animation and never load. Did you simply copy the comment’s changes and nothing else @vandres?

Hey folks,

Could you please all try out the following canary release?

npx storybook@0.0.0-pr-31759-sha-5376b07e upgrade

@Cybertron01Z thanks a lot for the tip. I followed the steps you mentioned and I can confirm that this works fine with tailwindcss v4.

I had missed renaming the tailwind.config.js because of which it wasn’t working before.